You are on page 1of 83

Web Application

Security Threats
and
Counter Measures

Sang Shin
sang.shin@sun.com
www.javapassion.com
Java Technology Evangelist
Sun Microsystems, Inc.

Exact File Name 11/11/07 Page 1


Today's Presentation is available from
http://www.javapassion.com

Demo is available from


http://www.javapassion.com/handsonlabs/
4010_webappsecurity.zip

Exact File Name 11/11/07 Page 2


Agenda
• How real is the Web application threat?
• 10 most common Web application threats and
counter measures
• Security principles
• Tools

. 3

Exact File Name 11/11/07 Page 3


95% of Web Apps Have
Vulnerabilities

• Cross-site scripting (80 percent)


• SQL injection (62 percent)
• Parameter tampering (60 percent)
• Cookie poisoning (37 percent)
• Database server (33 percent)
• Web server (23 percent)
• Buffer overflow (19 percent)

. 4

Source: http://www.vnunet.com/news/1152521

Exact File Name 11/11/07 Page 4


OWASP Top 10 Web Security Threats
1. Unvalidated input
2. Broken access control
3. Broken authentication
4. Cross-site scripting (XSS)
5. Buffer overflows
6. Injection flaws
7. Improper error handling
8. Insecure storage
9. Application denial-of-service
10. Insecure configuration management

Source: www.owasp.org
. 5

Exact File Name 11/11/07 Page 5


#1: Unvalidated
Input: Mother of
All Web-tier
Security Threats

Exact File Name 11/11/07 Page 6


#1: Unvalidated Input (Description)
• Attacker can easily tamper any part of the HTTP request
before submitting
> URL
> Cookies
> Form fields
> Hidden fields
> Headers
• Common names for common input tampering attacks
> forced browsing, command insertion, cross site scripting, buffer
overflows, format string attacks, SQL injection, cookie
poisoning, and hidden field manipulation

. 7

.Web applications use input from HTTP requests (and


occasionally files) to determine how to respond. Attackers
can tamper with any part of an HTTP request, including the
url, querystring,
Exact File Name headers, cookies, form fields, and hidden
11/11/07 Page 7
fields, to try to bypass the site’s security mechanisms.
Common names for common input tampering attacks include:
forced browsing, command insertion, cross site scripting,
buffer overflows, format string attacks, SQL injection, cookie
poisoning, and hidden field manipulation. Each of these
attack types is described in more detail later in this paper.

* A4 – Cross Site Scripting Flaws discusses input that


contains scripts to be executed on other user ’s browsers
* A5 – Buffer Overflows discusses input that has been
designed to overwrite program execution space
* A6 – Injection Flaws discusses input that is modified to
contain executable commands
#1: Unvalidated Input (Solutions)

• Do rigorous input data validation


> All parameters should be validated before use
• Do server-side validation
> Client side validation could be bypassed by the
attacker easily
> Client side validation is to be used mainly for quick
user responsiveness
• Do canonicalization of input data
> The process of simplifying the encoding

. 8

.Web applications use input from HTTP requests (and


occasionally files) to determine how to respond. Attackers
can tamper with any part of an HTTP request, including the
url, querystring,
Exact File Name headers, cookies, form fields, and hidden
11/11/07 Page 8
fields, to try to bypass the site’s security mechanisms.
Common names for common input tampering attacks include:
forced browsing, command insertion, cross site scripting,
buffer overflows, format string attacks, SQL injection, cookie
poisoning, and hidden field manipulation. Each of these
attack types is described in more detail later in this paper.

* A4 – Cross Site Scripting Flaws discusses input that


contains scripts to be executed on other user ’s browsers
* A5 – Buffer Overflows discusses input that has been
designed to overwrite program execution space
* A6 – Injection Flaws discusses input that is modified to
contain executable commands
#1: Unvalidated Input (Solutions)

• Use centralized code for input validation


> Scattered code is hard to maintain
• Each parameter should be checked against a
strict format that specifies exactly what input will
be allowed
> This is called “positive” input validation
> “Negative” approaches that involve filtering out certain
bad input or approaches that rely on signatures are not
likely to be effective and may be difficult to maintain

. 9

Exact File Name 11/11/07 Page 9


#1: Unvalidated Input (Solutions)
• Validation Criteria
> Data type (string, integer, real, etc…)
> Allowed character set
> Minimum and maximum length
> Whether null is allowed
> Whether the parameter is required or not
> Whether duplicates are allowed
> Numeric range
> Specific legal values (enumeration)
> Specific patterns (regular expressions)

. 10

Exact File Name 11/11/07 Page 10


What’s Wrong With This Picture?

. 11

Exact File Name 11/11/07 Page 11


#1: Unvalidated Input (Example)
public void doPost(HttpServletRequest req,…) {
String customerId =
req.getParameter(“customerId”);
String sku = req.getParameter(“sku”);
String stringPrice = req.getParameter(“price”);
Integer price = Integer.valueOf(stringPrice);
// Store in the database without input validation
// What happens if a hacker provides his own
// price as a value of “price” form field?
orderManager.submitOrder(sku,customerId,price);
} // end doPost
. 12

The problem here is that the price is being grabbed directly from the request input
(req.getParameter(“price”)).

Exact File Name 11/11/07 Page 12


#1: Unvalidated Input (Corrected)
public void doPost(HttpServletRequest req,…) {
// Get customer data
String customerId =
req.getParameter(“customerId”);
String sku = req.getParameter(“sku”);
// Get price from database
Integer price = skuManager.getPrice(sku);
// Store in the database
orderManager.submitOrder(sku,customerId,price);
} // end doPost

. 13

Rather than getting the price from the request, the solution is to get the price from the
database, flagging an error if it does not match what’s on the page. This is accomplished
with the call “skuManager.getPrice(sku)”

Exact File Name 11/11/07 Page 13


#1: Unvalidated Input (Tools)

• OWASP’s WebScarab
> By submitting unexpected values in HTTP requests
and viewing the web application’s responses, you
can identify places where tainted parameters are
used
• Stinger HTTP request validation engine
(stinger.sourceforge.net)
> Developed by OWASP for J2EE environments

. 14

Exact File Name 11/11/07 Page 14


#2: Broken
Access Control

Exact File Name 11/11/07 Page 15


#2: Broken Access Control
(Examples)

• Insecure ID's
• Forced browsing pass access control checking
• Path traversal
• File permissions

. 16

* Insecure Id’s – Most web sites use some form of id, key, or index as a
way to reference users, roles, content, objects, or functions. If an
attacker can guess these id’s, and the supplied values are not validated
to ensure the
Exact File are authorized for the
Name current user, the attacker can
11/11/07 Page 16
exercise the access control scheme freely to see what they can access.
Web applications should not rely on the secrecy of any id’s for
protection.
* Forced Browsing Past Access Control Checks – many sites require
users to pass certain checks before being granted access to certain
URLs that are typically ‘deeper’ down in the site. These checks must not
be bypassable by a user that simply skips over the page with the
security check.
* Path Traversal – This attack involves providing relative path
information (e.g., “../../target_dir/target_file”) as part of a request for
information. Such attacks try to access files that are normally not
directly accessible by anyone, or would otherwise be denied if requested
directly. Such attacks can be submitted in URLs as well as any other
input that ultimately accesses a file (i.e., system calls and shell
commands).
* File Permissions – Many web and application servers rely on access
control lists provided by the file system of the underlying platform. Even
if almost all data is stored on backend servers, there are always files
stored locally on the web and application server that should not be
publicly accessible, particularly configuration files, default files, and
scripts that are installed on most web and application servers. Only files
that are specifically intended to be presented to web users should be
marked as readable using the OS’s permissions mechanism, most
directories should not be readable, and very few files, if any, should be
marked executable.
* Client Side Caching – Many users access web applications from shared
computers located in libraries, schools, airports, and other public
access points. Browsers frequently cache web pages that can be
accessed by attackers to gain access to otherwise inaccessible parts of
. 17

Exact File Name 11/11/07 Page 17


#3: Broken
Authentication &
Session
Management

Exact File Name 11/11/07 Page 18


#3: Broken Authentication &
Session Management

• Includes all aspects of handling user


authentication and managing active sessions
• Session hi-jacking
> If the session tokens (Cookies) are not properly
protected, an attacker can hijack an active session
and assume the identity of a user

. 19

Exact File Name 11/11/07 Page 19


#3: Broken Account/Session
Management (Client Example—SSO)
public void doGet(HttpServletRequest req,…) {
// Get user name
String userId = req.getRemoteUser();
// Generate cookie with no encryption
Cookie ssoCookie =
new Cookie(“userid”,userId);
ssoCookie.setPath(“/”);
ssoCookie.setDomain(“cisco.com”);
response.addCookie(ssoCookie);

} . 20

Notice that the Cookie is stored with the plain-text userid of the
logged in user. In this example, the application that expects to
share a cookie with this system (shown on the next slide), will
find theExact File Namestored in plain text.
cookie 11/11/07 Page 20
#3: Broken Account/Session
Management (Server Example—SSO)
public void doGet(HttpServletRequest req,…) {
// Get user name
Cookie[] cookies = req.Cookies();
for (i=0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(“ssoCookie”)) {
String userId = cookie.getValue();
HttpSession session = req.getSession();
session.setAttribute(“userId”,userId);
} // end if
} // end for
} // end doGet
. 21

Here, the user is set from a plain-text cookie that was passed by
the client. Obviously, that cookie could have been spoofed.
Exact File Name 11/11/07 Page 21
#3: Safe Account/Session
Management (Client Solution—SSO)
public void doGet(HttpServletRequest req,…) {
// Get user name
String userId = req.getRemoteUser();
// Encrypt the User ID before passing it
// to the client as part of a cookie.
encryptedUserId = Encrypter.encrypt(userId);
Cookie ssoCookie =
new Cookie(“userid”,encrypteduserId);
ssoCookie.setPath(“/”);
ssoCookie.setDomain(“cisco.com”);
response.addCookie(ssoCookie);
… . 22

Now, the cookie is encrypted with a standard encryption library


to protect the contents from spoofing.
Exact File Name 11/11/07 Page 22
#3: Safe Account/Session
Management (Server Solution—SSO)
public void doGet(HttpServletRequest req,…) {
// Get user name
Cookie[] cookies = req.Cookies();
for (i=0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(“ssoCookie”)) {
String encryptedUserId = cookie.getValue();
String userId = Encrypter.decrypt(encryptedUserId);
if (isValid(userId)) {
HttpSession session = req.getSession();
session.setAttribute(“userId”,userId);
} // end if isValid…
} // end if cookie = ssoCookie…
} // end for
} // end doGet

. 23

Here, the user is first decrypted before being accepted as the user’s identity. Obviously, if
the cookie doesn’t decrypt to a valid value (checked by the “isValid” method), it won’t
allow the user’s cookie to be set properly, which is a good security check.

Exact File Name 11/11/07 Page 23


#4 Cross Site
Scripting (XSS)

Exact File Name 11/11/07 Page 24


#4: Cross Site Scripting (Description)
• An attacker can use cross site scripting technique to
implement malicious script (into a server), which is
then sent to unsuspecting users accessing the same
server
> Example: Chat server
• The attacked user’s (victim's) browser has no way to
know that the script should not be trusted, and will
execute the script
> Because it thinks the script came from a trusted source, the
malicious script can access any cookies, session tokens, or
other sensitive information retained by your browser and used
with that site
> These scripts can even rewrite the content of the HTML page
. 25

Exact File Name 11/11/07 Page 25


#4: Cross Site Scripting
(Description)
• XSS attacks usually come in the form of embedded
JavaScript
> However, any embedded active content is a potential source of
danger, including: ActiveX (OLE), VBscript, Shockwave, Flash
and more

. 26

Exact File Name 11/11/07 Page 26


#4: Consequences of Cross Site
Scripting (Examples)

• Disclosure of the user’s session cookie –


session high-jacking
• Disclosure of end user files
• Installation of Trojan horse programs
• Redirecting the user to some other page or
site
• Modifying presentation of content

. 27

Exact File Name 11/11/07 Page 27


#4: Cross Site Scripting
(How to Find them)
• Search for all places where input from an HTTP
request could possibly make its way into the
HTML output

. 28

Exact File Name 11/11/07 Page 28


#4: Cross Site Scripting
(Counter Measures)
• Validate all inputs, especially those inputs that
will later be used as parameters to OS
commands, scripts, and database queries
• It is particularly important for content that will be
permanently stored somewhere
• Users should not be able to create message
content that could cause another user to load an
undesireable page or undesireable content when
the user's message is retrieved
. 29

Exact File Name 11/11/07 Page 29


#4: Cross Site Scripting
(Counter Measures)
• Validate input against a rigorous positive
specification of what is expected
> Validation of all headers, cookies, query strings, form
fields, and hidden fields (i.e., all parameters) against a
rigorous specification of what should be allowed
> ‘Negative’ or attack signature based policies are difficult
to maintain and are likely to be incomplete
> White-listing: a-z, A-Z, 0-9, etc.
> Truncate input fields to reasonable length

. 30

Exact File Name 11/11/07 Page 30


#4: Cross Site Scripting (Counter Measures)
• Encode user supplied output
> Preventing inserted scripts from being transmitted to users in
an executable form
• Applications can gain significant protection from
javascript based attacks by converting the
following characters in all generated output to
the appropriate HTML entity encoding:
> from “<” to “&lt;”
> from “>” to “&gt;”
> from “(” to “&#40;”
> from “)” to “&#41;”
> from “#” to “&#35;”
> from “&” to “&#38;”
. 31

Exact File Name 11/11/07 Page 31


#4: Cross-Site Scripting (Flawed)
protected void doPost(HttpServletRequest req, HttpServletResponse res)
{
String title = req.getParameter(“TITLE”);
String message = req.getParameter(“MESSAGE”);
try {
connection = DatabaseUtilities.makeConnection(s);
PreparedStatement statement =
connection.prepareStatement(“INSERT INTO messages VALUES(?,?)”);
// The “title” and “message” are saved into
// the database. These “title” and “message”
// might contain ill-intended JavaScript.
statement.setString(1,title);
statement.setString(2,message);
statement.executeUpdate();
} catch (Exception e) {

} // end catch
} // end doPost . 32

The flaw here is that the values are taken directly from the
request and placed into the database, with no input validation or
sanitizing.
Exact File Name 11/11/07 Page 32
#4: Cross-Site Scripting (Solution)
private static String stripEvilChars(String evilInput) {
Pattern evilChars = Pattern.compile(“[^a-zA-Z0-9]”);
return evilChars.matcher(evilInput).replaceAll(“”);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
// Do vigorous input validation
String title = stripEvilChars(req.getParameter(“TITLE”));
String message = stripEvilChars(req.getParameter(“MESSAGE”));
try {
connection = DatabaseUtilities.makeConnection(s);
PreparedStatement statement =
connection.prepareStatement
(“INSERT INTO messages VALUES(?,?)”);
statement.setString(1,title);
statement.setString(2,message);
statement.executeUpdate();
} catch (Exception e) {

} // end catch
} // end doPost
. 33

To fix this, add the “stripEvilChars” method that uses JDK 1.4’s
pattern matching with regular expressions.
Exact File Name 11/11/07 Page 33
Cross Site
Scripting Demo

Exact File Name 11/11/07 Page 34


Demo Scenario (Stored XSS)
• The server is a chat server
• The chat server displays whatever message that is
typed in by a particular user to all other users
• An attacker (user A) implements JavaScript as part
of a message (message A)
• The chat server saves the message (into the
database or whatever storage) without input
validation
• When unsuspecting user (user B) reads the
message A, the JavaScript will be executed
. 35

J.

Exact File Name 11/11/07 Page 35


Demo Scenario (Reflected XSS)
• Whatever typed in by a user is reflected back to a
browser
• A mal-intended JavaScript will be reflected back to a
browser

. 36

J.

Exact File Name 11/11/07 Page 36


#5 Buffer Overflow

Exact File Name 11/11/07 Page 37


#5: Buffer Overflow Errors (Description)
• Attackers use buffer overflows to corrupt the
execution stack of a web application
> By sending carefully crafted input to a web application, an
attacker can cause the web application to execute
arbitrary code
• Buffer overflow flaws can be present in both the web
server or application server products or the web
application itself
• Not generally an issue with Java apps
> Java type checking
. 38

Exact File Name 11/11/07 Page 38


#6 Injection Flaws

Exact File Name 11/11/07 Page 39


#6: Injection Flaws (Description)
• Injection flaws allow attackers to relay malicious
code through a web application to another system
> Calls to the operating system via system calls
> The use of external programs via shell commands
> Calls to backend databases via SQL (i.e., SQL injection)
• Any time a web application uses an interpreter of
any type, there is a danger of an injection attack

. 40

J.

Exact File Name 11/11/07 Page 40


#6: Injection Flaws (Description)
• Many web applications use operating system
features and external programs to perform their
functions
> Runtime.exec() to external programs (like sendmail)
• When a web application passes information from an
HTTP request through as part of an external
request, the attacker can inject special (meta)
characters, malicious commands, or command
modifiers into the information

. 41

Exact File Name 11/11/07 Page 41


#6: Injection Flaws (Example)
• SQL injection is a particularly widespread and
dangerous form of injection
> To exploit a SQL injection flaw, the attacker must find a
parameter that the web application passes through to a
database
> By carefully embedding malicious SQL commands into
the content of the parameter, the attacker can trick the
web application into forwarding a malicious query to the
database

. 42

Exact File Name 11/11/07 Page 42


#6: Injection Flaws (Examples)
• Path traversal
> “../” characters as part of a filename request
• Additional commands could be tacked on to the end
of a parameter that is passed to a shell script to
execute an additional shell command
> “; rm –r *”
• SQL queries could be modified by adding additional
‘constraints’ to a where clause
> “OR 1=1”

. 43

Exact File Name 11/11/07 Page 43


#6: Injection Flaws (How to find them)
• Search the source code for all calls to external
resources
> e.g., system, exec, fork, Runtime.exec, SQL queries, or
whatever the syntax is for making requests to interpreters
in your environment

. 44

Exact File Name 11/11/07 Page 44


#6: Injection Flaws (Counter Measures)
• Avoid accessing external interpreters wherever possible
> Use library API's instead
• Structure many requests in a manner that ensures that all
supplied parameters are treated as data, rather than
potentially executable content
> For SQL, use PreparedStatement or Stored procedures
• Ensure that the web application runs with only the
privileges it absolutely needs to perform its function

. 45

The simplest way to protect against injection is to avoid accessing


external interpreters wherever possible. For many shell commands and
some system calls, there are language specific libraries that perform the
Exact File Name Using such libraries
same functions. 11/11/07 Page 45
does not involve the operating
system shell interpreter, and therefore avoids a large number of
problems with shell commands.

For those calls that you must still employ, such as calls to backend
databases, you must carefully validate the data provided to ensure that it
does not contain any malicious content. You can also structure many
requests in a manner that ensures that all supplied parameters are
treated as data, rather than potentially executable content. The use of
stored procedures or prepared statements will provide significant
protection, ensuring that supplied input is treated as data. These
measures will reduce, but not completely eliminate the risk involved in
these external calls. You still must always validate such input to make
sure it meets the expectations of the application in question.

Another strong protection against command injection is to ensure that


the web application runs with only the privileges it absolutely needs to
perform its function. So you should not run the webserver as root or
access a database as DBADMIN, otherwise an attacker can abuse these
administrative privileges granted to the web application. Some of the
J2EE environments allow the use of the Java sandbox, which can
prevent the execution of system commands.
#6: SQL Injection (Counter Measures)
• When making calls to backend databases, carefully
validate the data provided to ensure that it does not
contain any malicious content
• Use PreparedStatement or Stored procedures

. 46

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 46
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
SQL Injection Demo

Exact File Name 11/11/07 Page 47


Demo Scenario
• A user access database through a web server to
view his creditcard number by giving a userid
• A web server builds an SQL query to the database
server using the user-entered userid without
performing an input validation
• An attacker sends “.. OR 1=1” as part of userid
• The database server displays all users

. 48

J.

Exact File Name 11/11/07 Page 48


#7: Improper Error
Handling

Exact File Name 11/11/07 Page 49


#7: Improper Error Handling
(Description)
• The most common problem is when detailed internal error
messages such as stack traces, database dumps, and error
codes are displayed to a potential hacker
> These messages reveal implementation details that should never be
revealed
• Other errors can cause the system to crash or consume
significant resources, effectively denying or reducing service
to legitimate users
• Left-over during debugging process
• Inconsistent errors may reveal internal info.
> “File not found” vs. “Access denied”

. 50

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 50
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#7: Improper Error Handling (Counter
Measures)
• The errors must be handled according to a well
thought out scheme that will
> provide a meaningful error message to the user
> provide diagnostic information to the site maintainers
> provide no useful information to an attacker
• All security mechanisms should deny access until
specifically granted, not grant access until denied

. 51

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 51
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#7: Improper Error Handling (Counter
Measures)
• Good error handling mechanisms should be able to
handle any feasible set of inputs, while enforcing
proper security
• Error handling should not focus solely on input
provided by the user, but should also include any
errors that can be generated by internal components
such as system calls, database queries, or any other
internal functions

. 52

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 52
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#7: Improper Error Handling (Counter
Measures)
• A specific policy for how to handle errors should be
documented, including
> The types of errors to be handled
> For each, what information is going to be reported back to
the user
> What information is going to be logged
• All developers need to understand the policy and
ensure that their code follows it
> An architect should play a role of coming up and
enforcing a company-wide policy
. 53

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 53
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#7: Improper Error Handling (Counter
Measures)
• In the implementation, ensure that the site is built to
gracefully handle all possible errors.
> When errors occur, the site should respond with a
specifically designed result that is helpful to the user
without revealing unnecessary internal details.
> Certain classes of errors should be logged to help detect
implementation flaws in the site and/or hacking attempts.

. 54

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 54
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#7: Improper Error Handling (Counter
Measures)
• Very few sites have any intrusion detection
capabilities in their web application, but it is certainly
conceivable that a web application could track
repeated failed attempts and generate alerts
> Note that the vast majority of web application attacks are
never detected because so few sites have the capability
to detect them. Therefore, the prevalence of web
application security attacks is likely to be seriously
underestimated

. 55

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 55
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
What’s Wrong With This Picture?

. 56

Exact File Name 11/11/07 Page 56


#7: Improper Error Handling (Flaw)
protected void doPost(HttpServletRequest req, HttpServletResponse res)
{
String query =
"SELECT userid, name FROM user_data WHERE accountnum = '"
+ req.getParameter(“ACCT_NUM”) + “’”;
PrintWriter out = res.getWriter();
// HTML stuff to out.println…
try {
connection = DatabaseUtilities.makeConnection(s);
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(query);
while (results.next()) {
out.println("<TR><TD>“ + rset.getString(1) + “</TD>”);
out.println("<TD>“ + rset.getString(2) + “</TD>”);
} // end while
} catch (Exception e) {
e.printStackTrace(out);
} // end catch
} // end doPost . 57

The flaw here is that we are showing the entire stack trace to the user, which will certainly
help them in future attacks.

Exact File Name 11/11/07 Page 57


#7: Improper Error Handling (Solution)

protected void doPost(HttpServletRequest req, HttpServletResponse res)


{
String query =
"SELECT userid, name FROM user_data WHERE accountnum = '"
+ req.getParameter(“ACCT_NUM”) + “’”;
PrintWriter out = res.getWriter();
// HTML stuff to out.println…
try {
connection = DatabaseUtilities.makeConnection(s);
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(query);
while (results.next ()) {
out.println("<TR><TD>“ + rset.getString(1) + “</TD>”);
out.println("<TD>“ + rset.getString(2) + “</TD>”);
} // end while
} catch (Exception e) {
Logger logger = Logger.getLogger();
logger.log(Level.SEVERE,”Error retrieving account number”,e);
out.println(“Sorry, but we are unable
. to retrieve this account”); 58
} // end catch

To fix this, log the stack trace to the system logs, but only show a generic error message
to the user.

Exact File Name 11/11/07 Page 58


#9 Application
Denial Of Service
(DOS)

Exact File Name 11/11/07 Page 59


#9: Application DOS (Description)
• Types of resources
> Bandwidth, database connections, disk storage, CPU, memory,
threads, or application specific resources
• Application level resources
> Heavy object allocation/reclamation
> Overuse of logging
> Unhandled exceptions
> Unresolved dependencies on other systems
> Web services
> Databases

. 60

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 60
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#9: Application DOS (How to
determine you vulnerability)
• Load testing tools, such as JMeter can generate web
traffic so that you can test certain aspects of how your
site performs under heavy load
> Certainly one important test is how many requests per
second your application can field
> Testing from a single IP address is useful as it will give
you an idea of how many requests an attacker will have
to generate in order to damage your site
• To determine if any resources can be used to create a
denial of service, you should analyze each one to see if
there is a way to exhaust it
. 61

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 61
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#9: Application DOS (Counter
Measures)
• Limit the resources allocated to any user to a bare
minimum
• For authenticated users
> Establish quotas so that you can limit the amount of load a
particular user can put on your system
> Consider only handling one request per user at a time by
synchronizing on the user’s session
> Consider dropping any requests that you are currently
processing for a user when another request from that user
arrives

. 62

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 62
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
#9: Application DOS (Counter
Measures)
• For un-authenticated users
> Avoid any unnecessary access to databases or other
expensive resources
> Caching the content received by un-authenticated users
instead of generating it or accessing databases to retrieve it
• Check your error handling scheme to ensure that an
error cannot affect the overall operation of the
application

. 63

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 63
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
Other Web
Applications
Security Threats

Exact File Name 11/11/07 Page 64


Other Web Application Security
Threats
• Unnecessary and Malicious Code
• Broken Thread Safety and Concurrent Programming
• Unauthorized Information Gathering
• Accountability Problems and Weak Logging
• Data Corruption
• Broken Caching, Pooling, and Reuse

. 65

To exploit a SQL injection flaw, the attacker must find a


parameter that the web application passes through to a
database. By carefully embedding11/11/07
Exact File Name
malicious SQL commands Page 65
into the content of the parameter, the attacker can trick the web
application into forwarding a malicious query to the database.
Broken Thread
Safety Demo

Exact File Name 11/11/07 Page 66


Demo Scenario
• A servlet uses static variable called currentUser to
set the username and then displays the value of it
• A servlet can be accessed by multiple clients
• A servlet is not written to be multi-thread safe
• The instance variable can be in race-condition
> Browser A sets the username to jeff
> Browser B sets the username to dave
> If these two browsers access the servlet almost at the
same time, both browsers display one of the two names

. 67

J.

Exact File Name 11/11/07 Page 67


Principles of
Secure
Programming

Exact File Name 11/11/07 Page 68


Principles of Secure Programming
1. Minimize attack surface area
2. Secure defaults
3. Principle of least privilege
4. Principle of defense in depth
5. Fail securely
6. External systems are insecure
7. Separation of duties
8. Do not trust security through obscurity
9. Simplicity
10.Fix security issues correctly
. 69

Exact File Name 11/11/07 Page 69


Minimize Attack Surface Area
• The aim for secure development is to reduce the
overall risk by reducing the attack surface area
• Every feature that is added to an application adds a
certain amount of risk to the overall application
> The value of adding a feature needs to be accessed from
security risk standpoint

. 70

Every feature that is added to an application adds a certain


amount of risk to the overall
application. The aim for secure development
Exact File Name 11/11/07
is to reduce the Page 70
overall risk by reducing
the attack surface area.
For example, a web application implements online help with a
search function. The
search function may be vulnerable to SQL injection attacks. If the
help feature was limited to authorized users, the attack likelihood is
reduced. If the help feature’s search
function was gated through centralized data validation routines, the
ability to perform
SQL injection is dramatically reduced. However, if the help feature
was re-written to
eliminate the search function (through better user interface, for
example), this almost
eliminates the attack surface area, even if the help feature was
available to the Internet
at large..
Secure Defaults
• There are many ways to deliver an “out of the
box” experience for users. However, by default,
the experience should be secure, and it should
be up to the user to reduce their security – if they
are allowed
• Example:
> By default, password aging and complexity should be
enabled
> Users might be allowed to turn off these two features to
simplify their use of the application

. 71

There are many ways to deliver an “out of the box” experience


for users. However, by default, the experience should be secure,
and it should be up to the user to 11/11/07
Exact File Name
reduce their security – if they Page 71
are allowed.

For example, by default, password aging and complexity should


be enabled. Users might be allowed to turn these two features
off to simplify their use of the application and increase their risk.
Principle of Least Privilege
• Accounts have the least amount of privilege
required to perform their business processes.
> This encompasses user rights, resource
permissions such as CPU limits, memory, network,
and file system permissions
• Example
> If a middleware server only requires access to the
network, read access to a database table, and the
ability to write to a log, this describes all the
permissions that should be granted

. 72

The principle of least privilege recommends that accounts have


the least amount of
privilege required to perform their11/11/07
Exact File Name
business processes. This Page 72
encompasses user rights,
resource permissions such as CPU limits, memory, network,
and file system
permissions.

For example, if a middleware server only requires access to the


network, read access to
a database table, and the ability to write to a log, this describes
all the permissions that
should be granted. Under no circumstances should the
middleware be granted
administrative privileges.
Principle of Defense In Depth
• Controls, when used in depth, can make severe
vulnerabilities extraordinarily difficult to exploit
and thus unlikely to occur.
> With secure coding, this may take the form of tier-
based validation, centralized auditing controls, and
requiring users to be logged on all pages

. 73

Exact File Name 11/11/07 Page 73


Fail Safely
• Applications regularly fail to process transactions
for many reasons. How they fail can determine if an
application is secure or not
• Example: In the code below, if codeWhichMayFail()
fails, the attacker gets an admin priviledge

isAdmin = true;
try {
codeWhichMayFail();
isAdmin = isUserInRole( “Administrator” );
}
catch (Exception ex) {
log.write(ex.toString());
}

. 74

Exact File Name 11/11/07 Page 74


External Systems Are Insecure
• Implicit trust of externally run systems is not
warranted
> All external systems should be treated in a similar
fashion
• Example:
> A loyalty program provider provides data that is
used by Internet Banking, providing the number of
reward points and a small list of potential
redemption items
> However, the data should be checked to ensure
that it is safe to display to end users, and that the
reward points are a positive number, and not
improbably large
. 75

Exact File Name 11/11/07 Page 75


Separation of Duties
• A key fraud control is separation of duties
• Certain roles have different levels of trust than
normal users
> In particular, Administrators are different to normal
users. In general, administrators should not be users of
the application
• Example
> An administrator should be able to turn the system on
or off, set password policy but shouldn’t be able to log
on to the storefront as a super privileged user, such as
being able to “buy” goods on behalf of other users.

. 76

Exact File Name 11/11/07 Page 76


Do Not Trust Security Through
Obscurity
• Security through obscurity is a weak security
control, and nearly always fails when it is the only
control
> This is not to say that keeping secrets is a bad idea, it
simply means that the security of key systems should
not be reliant upon keeping details hidden
• Example
> The security of an application should not rely upon only
on knowledge of the source code being kept secret
> The security of an application should rely upon many
other factors, including reasonable password policies,
defense in depth, business transaction limits, solid
network architecture, and fraud and audit controls
. 77

Exact File Name 11/11/07 Page 77


Simplicity
• Attack surface area and simplicity go hand in
hand. Certain software engineering fads prefer
overly complex approaches to what would
otherwise be relatively straightforward and simple
code.
• Example
> Although it might be fashionable to have a slew of
singleton entity beans running on a separate
middleware server, it is more secure and faster to
simply use global variables with an appropriate mutex
mechanism to protect against race conditions.

. 78

Exact File Name 11/11/07 Page 78


Fix Security Issues Correctly
• Once a security issue has been identified, it is
important to develop a test for it, and to understand
the root cause of the issue
• Example
> A user has found that they can see another user’s
balance by adjusting their cookie. The fix seems to
be relatively straightforward, but as the cookie
handling code is shared amongst all applications,
a change to just one application will trickle through
to all other applications. The fix must therefore be
tested on all affected applications.

. 79

Exact File Name 11/11/07 Page 79


Tools!

Exact File Name 11/11/07 Page 80


Tools
• WebScarab - a web application vulnerability
assessment suite including proxy tools
• Validation Filters – (Stinger for J2EE, filters for
PHP) generic security boundary filters that
developers can use in their own applications
• CodeSpy – look for security issues using
reflection in J2EE apps

. 81

Exact File Name 11/11/07 Page 81


Tools
• CodeSeeker - an commercial quality application
level firewall and Intrusion Detection System that
runs on Windows and Linux and supports IIS,
Apache and iPlanet web servers,
• WebGoat - an interactive training and
benchmarking tool that users can learn about
web application security in a safe and legal
environment
• WebSphinx – web crawler looking for security
issues in web applications
• OWASP Portal - our own Java based portal code
designed with security as a prime concern
. 82

Exact File Name 11/11/07 Page 82


Web Application
Security Threats
and Counter
Measures

Sang Shin
sang.shin@sun.com
www.javapassion.com
Java Technology Evangelist
Sun Microsystems, Inc.

Exact File Name 11/11/07 Page 83

You might also like