Sie sind auf Seite 1von 99

COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Hong Kong Polytechnic University


Department of Computing

COMP444 Internet Infrastructure Security


Group Project Report

OWASP WebGoat Project

To: Dr. Rocky K. C. Chang

From: Li Wai Ping, Alice (05716341T)


Li Ka Chun, Alfred (05722507T)
Pierre Yves BEL (06003941X)
Tsui Ching Wah, Banly (04702363T)

Due Date: 16th May, 2007.


COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Contents

1. Introduction ........................................................... 1

1.1. Internet Security Issue............................................................ 1

1.2. What is WebGoat Project? ....................................................... 2

2. Broken Access Control (by Alfred) ......................... 3

2.1. Background.............................................................................. 3

2.1.1. Path Based Access Control Scheme ...................................... 4


2.1.2. Cross Site Request Forgery (CSRF) ....................................... 4
2.1.3. Remote Admin Access ......................................................... 5
2.2. Problem domain....................................................................... 5

2.3. Vulnerability Test in WebGoat ................................................. 6

2.3.1. Bypass a Path Based Access Control Scheme: ....................... 6


2.3.2. Perform Cross Site Request Forgery (CSRF) .......................... 9
2.3.3. Perform Remote Admin Access........................................... 12
2.4. Avoidance of Vulnerability ..................................................... 15

2.4.1. Bypass a Path Based on Access Control .............................. 15


2.4.2. Perform Cross Site Request Forgery (CSRF) ........................ 16
2.4.3. Remote Admin Access ....................................................... 16

3. Cross-Site Scripting (XSS) (by Banly) .................. 17

3.1. Background............................................................................ 17

3.2. Problem Domain .................................................................... 17


COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.3. Types of Vulnerability ............................................................ 18

3.3.1. Stored Cross-Site Scripting................................................. 18


3.3.2. Reflected Cross-Site Scripting............................................. 19
3.3.3. HTTPOnly......................................................................... 19
3.3.4. Cross Site Tracing (XST).................................................... 20
3.4. Vulnerability Test in WebGoat ............................................... 21

3.4.1. Stored Cross Site Scripting (XSS)........................................ 21


3.4.2. Reflected Cross Site Scripting............................................. 23
3.4.3. HTTPOnly......................................................................... 24
3.4.4. Cross Site Tracing (XST).................................................... 26
3.5. Avoidance of Vulnerability ..................................................... 27

3.5.1. Using HTML and URL encoding .......................................... 27


3.5.2. Implement HTTPOnly cookie option.................................... 28
3.5.3. Disable HTTP Trace support............................................... 28

4. Injection Flaws (by Alice) .................................... 29

4.1. Background............................................................................ 29

4.1.1. Structure Query Language (SQL)........................................ 29


4.1.2. Server Log........................................................................ 29
4.1.3. XML Path Language (XPATH) ............................................. 29
4.2. Problem Domain .................................................................... 30
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3. Vulnerability Test in WebGoat ............................................... 31

4.3.1. Blind SQL Injection ........................................................... 31


4.3.2. Numeric SQL Injection....................................................... 33
4.3.3. Log Spoofing .................................................................... 36
4.3.4. XPATH Injection................................................................ 38
4.3.5. String SQL Injection .......................................................... 40
4.3.6. Database Backdoors.......................................................... 42
4.4. Avoidance of Vulnerability ..................................................... 44

4.4.1. HTML............................................................................... 44
4.4.2. Java Script ....................................................................... 44
4.4.3. Java Servlet...................................................................... 45
4.4.4. Access Rights of SQL Server .............................................. 45
4.5. Implementation ..................................................................... 47

4.5.1. Web Server ...................................................................... 47


4.5.2. Database.......................................................................... 47
4.5.3. Programming Language..................................................... 47
4.5.4. Website............................................................................ 47
4.6. Evaluation .............................................................................. 48

4.6.1. Vulnerability via Web Browser ............................................ 48


4.6.2. Vulnerability via Tools ....................................................... 49

5. AJAX Security (by Pierre Yves)............................. 50

5.1. Background............................................................................ 50

5.1.1. DOM (Document Object Model).......................................... 51


5.1.2. XML ................................................................................. 51
5.1.3. JSON ............................................................................... 51
5.1.4. Javascript......................................................................... 51
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.2. Problem Domain .................................................................... 52

5.3. Vulnerability Test in WebGoat ............................................... 52

5.3.1. DOM Injection .................................................................. 52


5.3.2. XML/JSON Injection .......................................................... 56
5.3.3. JSON Injection.................................................................. 61
5.3.4. Silent Transaction ............................................................. 64
5.4. Avoidance of Vulnerability ..................................................... 66

5.4.1. Preventing the user from editing data................................. 67


5.4.2. Detecting attacks attempts ................................................ 68

6. Conclusion ............................................................ 70

7. Reference ............................................................. 71

7.1. Book....................................................................................... 71

7.2. Web Site ................................................................................ 71

8. Appendix............................................................... 72

8.1. Source Code File List.............................................................. 72

8.2. Oracle Table Structure ........................................................... 73

8.3. HTML with Java Script ........................................................... 74

8.4. Java ....................................................................................... 81


COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

1. Introduction

1.1. Internet Security Issue

Today, Internet security is still the hottest topic in our cyber world. Everyday,
thousand and thousand of security cases happen. These attacks are range from
different methods (physical or social engineering) to different technologies
(malicious software or fraudulent sites). Most of the times, attackers compromise
these methods and technologies into more than thousand variations of attack.

For web information security, although we have HTTPS connection to the remote
server to protect our information from eavesdropping, the attacker can still start the
attack that is originated from the client side.

In this report, we focus into the following area of technique that most attackers use
and compromise them at the client side.

a. Data Injection

Scripts or codes that injected into the server or client browsers that can retrieve
information on both entity environments: HTML, SQL, XML, Java Script, DOM,
JSON etc.

b. Legitimate user Forced Attacks

Browser of a legitimate user executes a malicious action without knowledge of


the server’s path structure. The attacker can inject script in the non-secure
webpage like the following

e.g.http://bank.com/transfer?amount=10000&ac=1234

Page 1 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

c. Broken Access Control

Although most web site built to require authentication if necessary, it is true that
not every authentication method is able to provide adequate security and most
of the time, the attack is originated from legitimate user through forced-attack.

When programmers or server administrators neglect or ignore this security


threat, the authentication schemes can be bypassed by simply skipping the login
page. The attacker directly calls the internal page that is supposed to be access
only after authentication has been performed. This relative path access results
to access non-authentication page.

The report demonstrates how these kinds of attack can be achieved by useful web
security training software WebGoat that is provided by the Open Web Application
Security Project (OWASP).

The following vulnerability tests are selected to demonstrate the above-mentioned


techniques:

a. Broken Access Control (by Alfred Li)

b. Cross-Site Scripting (XSS) (by Banly Tsui)

c. Injection Flaws (by Alice Li)

d. AJAX Security (by Pierre Yves)

1.2. What is WebGoat Project?

WebGoat provide a safe and legal environment to learn how to find the vulnerability
of web application. It is a deliberately insecure J2EE web application maintained by
the Open Web Application Security Project (OWASP). In each lesson, users must
demonstrate their understanding of a security issue by exploiting a real vulnerability
in the WebGoat application.

For example, in one of the lessons the user must use SQL injection to steal fake
credit card numbers. The application is a realistic teaching environment, providing
users with hints and code to further explain the lesson.

Page 2 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2. Broken Access Control (by Alfred)

2.1. Background

Access control, sometimes called authorization, it is the meaning by which a web


application grants access to specified content and functions to some users and not
others. Access control manages what "authorized" users are allowed to do. Access
control sounds like a simple problem but is insidiously difficult to implement
correctly. A web application access control model is closely tied to the content and
functions that the site provides. In addition, the users may fall into a number of
groups or roles, with different abilities or privileges.

Typically, authentication must pre-process before authorization. Authentication


verifies the identity of a user. Authorization is the process of attempting to verify
the digital identity of the sender of a communication such as a request to log in.
The sender being authenticated may be a person using a computer, a computer
itself or a computer program, then used to determine what that user is allowed to
access. To ensure proper access control, a web application must ensure both that it
has proper authorization checks, and that it is using reliable and secure
authentication that can distinguish privileged users from others, including random
strangers on the Internet.

Developers frequently underestimate the difficulty of implementing a reliable access


control mechanism. Many access control schemes were not deliberately designed,
but have simply evolved along with the web site. In these cases, access control
rules are inserted in various locations all over the code. As the site nears
deployment, the ad hoc collection of rules becomes so unwieldy that it is almost
impossible to understand.

Many of these flawed access control schemes are not difficult to discover and
exploit. Frequently, all that is required is to craft a request for functions or content
that should not be granted. Once a flaw is discovered, the consequences of a
flawed access control scheme can be devastating. In addition to viewing
unauthorized content, an attacker might be able to change or delete content,
perform unauthorized functions, or even take over site administration.

Page 3 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

One particularly dangerous type of access control vulnerability arises from Web-
accessible administrative interfaces. Such features are frequently used to allow site
administrators to efficiently manage users, data, and content on their site. In many
instances, sites support a variety of administrative roles to allow finer granularity of
site administration. Due to their power, these interfaces are frequently prime
targets for attack by both outsiders and insiders.

To help understanding the problems, we will first explain shortly on different


aspects of the technologies about Access Control on the Web Page:

2.1.1. Path Based Access Control Scheme

Web servers generally are set up to restrict public access to a specific


portion of the Web server's file system, typically called the "Web document
root" directory. This directory contains the files intended for public access
and any scripts necessary to provide Web application functionality.

Many web applications use and manage files as part of their daily operation.
Using input validation methods that have not been well designed or
deployed, an aggressor could exploit the system in order to read/write files
that are not intended to be accessible; in particular situations it could be
possible to execute arbitrary code or system commands.

2.1.2. Cross Site Request Forgery (CSRF)

CSRF forces legitimate users to execute commands without their consent.


This type of attack is extremely hard to prevent unless the application is
free of cross-site scripting vectors, including DOM injections. With the rise
of Ajax techniques, and better knowledge of how to properly exploit XSS
attacks, CSRF attacks are becoming extremely sophisticated, both as an
active individual attack and as automated worms, such as the Samy
MySpace Worm.

CSRF is looking similar to Cross-Site Scripting (XSS), but it is not the same.
XSS aimed at inserting active code in an HTML document to either abuse
client-side active scripting holes, or to send privileged information (e.g.
authentication/session cookies) to a previously unknown evil collection site.
On the other hand CSRF does not in any way rely on client-side active
scripting, and its aim is to take unwanted, unapproved actions on a site
where the victim has some prior relationship and authority.

Page 4 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.1.3. Remote Admin Access

The Remote Admin Access is meaning that there is a page which using to
provide administrator level functions and they are appropriately segregated
from user activity for the application administrator.

Many products and applications using web interface, including security


products, rely on the trusted nature of the environment in which they
operate to maintain security. The products' designers assume that only
authorized systems or users can gain access to the administrative interfaces,
so they do not develop code to protect application interfaces from
unauthorized access. The administrators who are unaware of this
vulnerability, may allow remote access to administrative interfaces through
the internet, introducing a significant weakness.

2.2. Problem domain

In a path based access control attack or we can also called path traversal attack, an
intruder manipulates a URL in such a way that the Web server executes or reveals
the contents of a file anywhere on the server, including those lying outside the
document root directory. These attacks take advantage of special-characters
sequences in URL input parameters, cookies and HTTP request header.

The most basic path traversal attack uses the "../" character sequence to alter the
document or resource location requested in a URL. By this attack an attacker is able
read directory and files which normally he/she couldn't read, access data outside
the web document root, include scripts and other kinds of files from external
websites. On the other hand this attack also allowed an attacker to execute
operating system programs and tools.

Page 5 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.3. Vulnerability Test in WebGoat

Here are some examples of the attacks show in the WebGoat application.

2.3.1. Bypass a Path Based Access Control Scheme:

In a path based access control scheme, an attacker can traverse a path by


providing relative path information. Therefore an attacker can use relative paths to
access files that normally are not directly accessible by anyone, or would otherwise
be denied if requested directly.

For example we have the following page on a website:

This page is providing an environment for the user to view the content of the files
which have access right.

Page 6 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Normally the user can choose one of the file on the list then click on the “View File”
button to view the content of the file.

The content of the file will show at the bottom of the windows.

Page 7 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

We are now going to view the files that not intended to be accessible. For example
we would like to view the file on the path of the Web Server which does not
accessible for the user by default.

The attacker could insert the malicious string:


http://localhost/main.asp?menu=210&File=../../../LICENSE

The content of the file has display at the bottom of the windows. The file is not on
the list for the user by default. That means the attacker can access on some files
which is not accessible, so the attack is successful.

Page 8 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.3.2. Perform Cross Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF/XSRF) is an attack that tricks the victim into
loading a page that contains image links. When the victim's browser attempts to
render the page, it will issue a request with specified parameters to forces
legitimate users to execute unwanted and unapproved actions unknowingly.

For example we have the following page on a newsgroup/forum/blog:

The user can send a message on this web page after input some information on the
Title and the message box and chick the “Submit” button.

The user can view the message on the same page which submitted by the other
user before.

Page 9 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

The attacker is going to include an image tag in the content of the message. The
image tag is not including any image but the size is 30x30 pixels.

The user will see a broken image icon on the message 2.

Page 10 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

The attacker is going to include an action on the image tag and not allow the victim
to know the attack by making the image in 1x1 pixels. In this example the attacker
is going to make the victim’s browser to issue a request on a special link and
including an extra parameter for transferring the funds with the value “5000”.

The
victim's browser attempts to render the page and will authenticate to transfer the
funds at that same time. The victim cannot see any errors on the page as the result
he/she had executed unwanted and unapproved actions unknowingly. The attacker
has completed the attack in this example.

Page 11 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.3.3. Perform Remote Admin Access

Applications will often have an administrative interface that allows privileged user to
access some admin functionality that normal users should not see. The application
server will often have an admin interface as well for example the IIS or Tomcat
Web Server.

The attacker is going to access the administrative interface of the Web Server:

Many applications use a common path for administrative interfaces. In this example
the attacker is trying to access the Tomcat Web Server by input the path with the
“/admin”.

The attacker cannot view the administration page because the web server did not
install the “admin” package. But as we can get this result, it is meaning that the
attack is successful if the application already installed the package. The attacker
can get the chance to change the information on the web server.

Page 12 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

The attacker is going to access the administrative interface in the Web Goat
application:

Normally there are only one Admin Functions which call “Report Card” for normal
user. WebGoat has one admin interface that is controlled via a URL parameter and
is 'hackable'.

The hacker then add the value “&admin=true” at the end of the link.

After enter the link the attack can see three more admin functions called “Database
Dump”, Product Information” and “User Information”. Then the attacker will know
the actually link of the above functions.

Page 13 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

This is the link of the User Information. The attacker can directly input the link and
view the administrative page which allows privileged users access only.

The attacker can view some important information on the administrative page. For
example: User Id or Password.
As the result the attack is successful.

Page 14 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.4. Avoidance of Vulnerability

The most important step is to think through an application’s access control


requirements and capture it in a web application security policy. We strongly
recommend the use of an access control matrix to define the access control rules.
Without documenting the security policy, there is no definition of what it means to
be secure for that site. The policy should document what types of users can access
the system, and what functions and content each of these types of users should be
allowed to access. The access control mechanism should be extensively tested to be
sure that there is no way to bypass it. This testing requires a variety of accounts
and extensive attempts to access unauthorized content or functions.

We are now going to give some suggestion on each part of the Broken Access
Control attack on the Web application:

2.4.1. Bypass a Path Based on Access Control

Although most Web servers prevent this method from escaping the web document
root, alternate encodings of the "../" sequence, such as Unicode-encoding, can
bypass basic security filters. Even if a Web server properly restricts path traversal
attempts in the URL path, any application that exposes an HTTP-based interface is
also potentially vulnerable to such attacks.

The traversal attacks allow an attacker to execute the operating system programs
and tools, we should always locate the Web root directories and virtual directories
on a non-system partition. It's not possible to traverse across the other drives
beside the web root directories. For example, if the web application is installed on
the C: drive, consider moving the site and content directory to the E: drive, then we
can ensuring that all virtual directories point to the new drive. For a Windows-based
Web site this means never using the default \Inetpub\wwwroot directory for the
location of Web site content. This tactic also ensures that any future worm that
allows an attacker to access system files will fail.

The web developer should perform the input Vectors enumeration. In order to
determine which part of the application is vulnerable to input validation bypassing,
the developers needs to enumerate all part of the application which accept content
from the user. This also includes HTTP GET and POST queries and common options
like file uploads and html forms. On the other hand the developer should analyze
the input validation functions present into the web application.

Page 15 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

2.4.2. Perform Cross Site Request Forgery (CSRF)

We can divide into two parts for preventing CSRF, the parts responsible by users
and developers.

Users:
The users should not allow the browser to save the usernames or passwords. They
should not access sensitive applications like e-banking and surf the Internet at the
same time. On the other hand the users should“Log off" immediately after using
any authenticated Web site every time. The integrated HTML-enabled mail/browser,
newsreader/browser environments pose additional risks since simply viewing a mail
message or a news message might lead to the execution of an attack.

Developers:
The application can protect the attack by checking the HTTP Referer header. The
checking only allows those requests which appear to originate from valid URLs. This
would prevent things like attacks via email. But it would also mean locking out any
user whose requests did not contain Referer information.

The web application developer can also add an "argument map table" for each
session. For each user, the system might look for a random number as an argument
name instead of the predictable "action" or "body" as an action. It will result more
difficult to construct a valid URL for a CSRF malicious action.
Add session-related information.

The web application should use POST instead of GET. While POST requests may be
simulated by means of JavaScript, they make it more complex to mount an attack.
Automatic logout mechanisms could also help to prevent the attack.

2.4.3. Remote Admin Access

The Web Server administrator should ensure the administrative interfaces available
on the internal network only. The web application developer can also perform the
Web application discovery to identifying web applications on given infrastructure.
The web application should also perform some searching test by some tools like
Wikto or Googlegath.

Page 16 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3. Cross-Site Scripting (XSS) (by Banly)

3.1. Background

There have been several incidents in the Internet that about data theft from Google
Ads. It is because the malware-loaded web sites (with malicious script) are
embedded in the advertisement links and the web vulnerability compromises this
kind of attack.

“The attack targeted the top sponsored links tied to Google search results, installing
a program on victims' computers to capture private information used to access
online accounts for 100 different banks” – reported by MSNBC on 27th April 2007.

How the theft does his/her dirty job? The answer is Cross Site Scripting Attack,
which has been come with the Internet long time ago.

"Attackers have been doing this for some time _ the old dog is still doing old tricks
and it's working," he said. "We need to realize this is a known tactic, people should
be aware of it and identify when this could be an issue” – reported by MSNBC on
27th April 2007.

In this session, we would demonstrate four types of Cross Site Scripting test on web
vulnerability.

3.2. Problem Domain

Cross Site Scripting (XSS) is one of the most common application level attacks. XSS
are code injection attacks into the various interpreters in the browser. Since the
running of scripts in the client browser, the attacker can bypass access controls and
gather client information that may result in account hijacking, changing of client
settings, cookie theft/poisoning or false advertising.
These attacks can be carried out using HTML, JavaScript, VBScript, ActiveX, Flash
and other client-side languages.

In some XSS vulnerabilities can even perform other functions such as scanning for
other vulnerabilities and performing a Denial of Service on the web server. For
example, a script from one page should be able to access data from another page
or object when the client opens more than a web browser.

Page 17 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

XSS involves three parties, the attacker, a client and the web site. This kind of
attack can breach the security polices and results in the client details are stolen or
manipulated. The attacker steals the client cookies, or any other sensitive
information, which can be used for authentication to the web site. With the
legitimate client information, the attacker can impersonate the client to the web site.

The most common method is that the attacker posts malicious scripts onto online
message boards, web logs, guest books or user forums where messages can be
permanently stored. This kind of message is seemed to be harmless but encodes a
script that attacks the user once they click the link. This is also the reason why XSS
is commonly used in many Phishing attacks.

3.3. Types of Vulnerability

There are four XSS vulnerability test on WASAP WebGoat V5: Stored Cross-Site
Scripting, Reflected Cross-Site Scripting, HTTPOnly and Cross Site Tracing:

3.3.1. Stored Cross-Site Scripting

This vulnerability allows the most powerful kinds of attacks. This type of XSS
vulnerability exists when data provided to a web application by a user is first stored
persistently on the server (in a database, file system, or other location), and later
displayed to users in a web page without being encoded using HTML entities. A
classic example of this is with online message boards, where users are allowed to
post HTML formatted messages for other users to read.

These vulnerabilities are usually more significant than other types because an
attacker can inject the script just once. This could potentially hit a large number of
other users with little need for social engineering or a cross-site scripting virus could
even infect the web application.

The methods of injection can vary a great deal, and an attacker may not need to
use the web application itself to exploit such a hole. Any data received by the web
application (via email, system logs, etc) that can be controlled by an attacker must
be encoded prior to re-display in a dynamic page; else an XSS vulnerability of this
type could result.

Page 18 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.3.2. Reflected Cross-Site Scripting

This kind of vulnerability is by far the most common type. These holes show up
when data that is provided by a web client, is used immediately by server-side
scripts to generate a page of results for that user. If invalidated user-supplied data
is included in the resulting page without HTML encoding, this will allow client-side
code to be injected into the dynamic page. A classic example of this is in site search
engines: if one searches for a string which includes some HTML special characters,
often the search string will be redisplayed on the result page to indicate what was
searched for, or will at least include the search terms in the text box for easier
editing. If all occurrences of the search terms are not HTML entity encoded, an XSS
hole will result.

At first glance, this does not appear to be a serious problem since users can only
inject code into their own pages. However, with a small amount of social
engineering, an attacker could convince a user to follow a malicious URL which
injects code into the results page, giving the attacker full access to that page's
content. Due to the general requirement of the use of some social engineering in
this case (and normally in DOM-based XSS vulnerabilities as well), many
programmers have disregarded these holes as not terribly important. This
misconception is sometimes applied to XSS holes in general (even though this is
only one type of XSS) and there is often disagreement in the security community as
to the importance of cross-site scripting vulnerabilities.

3.3.3. HTTPOnly

HTTPOnly is a HTTP Cookie option used to inform the browser not to allow scripting
languages (JavaScript, VBScript, etc.) access to the “document.cookie” object
(normal XSS attack target).

Since the attribute is relatively new, several browsers neglect to handle the new
attribute properly.

Page 19 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.3.4. Cross Site Tracing (XST)

Although HTTPOnly cookies prevent the JavaScript from directly accessing the
cookies but the attacker was able to retrieve it through an indirect method.

TRACE is used simply as an input data echo mechanism for the http protocol. This is
a request method that is commonly used for debug and other connection analysis
activities. TRACE will echo the information you send in the HTTP Request. This
includes cookie and Web Authentication strings, since they are just simple HTTP
headers themselves.

The http trace request which containing request line, headers, post data, sent to a
trace supporting web server, will respond to the client with the information
contained in the request. Trace provides any easy to way to tell what an http client
is sending and what the server is receiving. Apache, IIS, and iPlanet all support
trace as defined by the HTTP/1.1 RFC and it is currently enabled by default. Very
few system administrators have disabled this request method either because the
method posed no known risk, default settings were considered good enough or
simply had no option to do so.

Page 20 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.4. Vulnerability Test in WebGoat

3.4.1. Stored Cross Site Scripting (XSS)

The message written in java script was posted into the message board, e.g. Test1:

The message title: Test1 was posted as hyper link:

When the message title was pressed, the script was being run on client browser:

Page 21 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Another message: Test2 using simple script tab to run in the browser by any
program:

The message: Test2 was posted:

When the message: Test2 was pressed, the script was run by the browser:

Page 22 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.4.2. Reflected Cross Site Scripting

In this test we get this page to reflect that input back to the browser, which will
execute the script and do something bad.

By the use of WebScarcab, we intercept the POST message when update or submit
the web information and enter the following code one of the field:

<SCRIPT>alert('bang!');</SCRIPT>

Original POST parameters:

QTY1=1&QTY2=1&QTY3=1&QTY4=1&SUBMIT=Update+
Cart&field2=4128+3214+0002+1999&field1=111

Edited POST parameters:

QTY1=1&QTY2=1&QTY3=1&QTY4=1&SUBMIT=Update+
Cart&field2=4128+3214+0002+1999&field1=111<SCRIPT>alert('bang!');</SCRIPT
>

Page 23 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

When the server responded, the script in modify field was being executed and
displayed on the screen.

3.4.3. HTTPOnly

The purpose of this test is to test whether the browser supports the HTTPOnly
cookie flag. Note the value of the unique2u cookie. If the browser supports
HTTPOnly, and we enable it for a cookie, client side code should NOT be able to
read OR write to that cookie, but the browser can still send its value to the server.
Some browsers only prevent client side read access, but don't prevent write access.

HTTPOnly was enable and “Read Cookie” button was press to test:

The session cookie was read and displayed:

Page 24 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

When the “Write Cookie” button was press to test, the cookie unique2u was being
modified and displayed:

The browser did not enforce the write protection property of the HTTPOnly flag for
the 'unique2u' cookie and the unique2u cookie was successfully modified to
HACKED on the client side.

Page 25 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.4.4. Cross Site Tracing (XST)

The following script was embedded in on of the input field by WebScarab:

<script type="text/javascript">
if ( navigator.appName.indexOf("Microsoft") !=-1) {
var xmlHttp = new
ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("TRACE", "./", false);
xmlHttp.send();
str1=xmlHttp.responseText;
str2=xmlHttp.status;
while (str1.indexOf("\n") > -1)
str1 = str1.replace("\n","<br>");
document.write(str1);
alert(str2);
}
</script>

When the server responded, the TRACE http command was run by XMLHttpRequest
in the browser successfully.

Page 26 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.5. Avoidance of Vulnerability

3.5.1. Using HTML and URL encoding

a. Any data input should be filtered and restricted from online forum and message
broad.

It always filters meta-characters ("special" characters) that are defined in the


HTML specification. Each input field, including link parameters will be validated
for script tags. When found and dependent on the context, the input will be
rejected and thus prevent the malicious HTML from being presented to the user.

Any data received by the web application should be encoded prior to re-display
in a dynamic page.

b. Adding to the complexity is that many Web browsers try to correct common
errors in HTML. As a result, they sometimes treat characters as special when,
according to the specification, they are not. Therefore, it is important to note
that individual situations may warrant including additional characters in the list
of special characters. Web developers must examine their applications and
determine which characters can affect their web applications.

Filtering on the input side is less effective because dynamic content can be
entered into a Web site database via methods other than HTTP. In this case, the
Web server may never see the data as part of the data input process and the
data elements still remain tainted. Alternatively, it is recommended that filtering
be done as part of the data output process, just before it is rendered as part of
the dynamic page. Done correctly, this approach ensures that all dynamic
content is filtered.

Cross-site scripting attacks can be avoided when a Web server adequately


ensures that generated pages are properly encoded to prevent unintended
execution of scripts. Each character in the ISO-8859-1 specification can be
encoded using its numeric entry value. Server side encoding is a process where
all dynamic content will go through an encoding function where scripting tags
will be replaced with codes in the chosen character set. Generally speaking,
encoding is recommended because it does not require you to make a decision
about what characters could legitimately be entered and need to be passed
through. Unfortunately, encoding all un-trusted data can be resource intensive
and may have a performance impact on some Web servers.

Page 27 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

3.5.2. Implement HTTPOnly cookie option

To implement HTTPOnly cookie option, it is browser specific. HTTPOnly begun from


Microsoft Internet Explorer 6.0 SP1 and HttpOnly blocks script access to the cookie
property (document.cookie), but does not prevent a scripting object from reading
the cookie out of an HTTP TRACE response.

3.5.3. Disable HTTP Trace support

To prevent Cross Site Tracing attack, it is recommended to disable HTTP TRACE


support in web servers. As a best practice, CERT/CC recommends limiting input
("whitelisting") to the minimum set of values required for proper operation of a
given application.

a. For Apache HTTP Server

Use the Apache mod_rewrite module to deny HTTP TRACE requests or to permit
only the methods needed to meet site requirements and policy. TRACE requests
can be disabled with the following mod_rewrite syntax:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^TRACE
RewriteRule .* - [F]

b. For Microsoft Internet Information Services (IIS)

Use the URLScan tool to deny HTTP TRACE requests or to permit only the
methods needed to meet site requirements and policy. The default
configurations of Urlscan 2.5 (both baseline and SRP) only permit GET and HEAD
methods.

Page 28 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4. Injection Flaws (by Alice)

4.1. Background

Injection is a kind of hacking technique that changes the normal operation by


appending coding. This situation most express in structural programming language.

4.1.1. Structure Query Language (SQL)

SQL stand for Structured Query Language that is a computer language. It used to
manipulate data of relational database management systems. These command
include create, retrieve, update and delete. SQL has been standardized by both
ANSI and ISO.[9]

4.1.2. Server Log

A lot of web system will have event log that register all user activity. This activity
information includes client IP address, active date and time, page requested and
HTTP code. [9].

4.1.3. XML Path Language (XPATH)

XPATH stands for XML Path Language that is an expression language for addressing
or computing of XML document. It is simple query language so have characteristic
as SQL statement. [9]

Page 29 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.2. Problem Domain

SQL database is most common to apply in web application. It provides capability


and reliability feature of performance. The easily and simply manipulate command
let development more efficient. This merit of SQL (or language have similar feature)
not only advantage developer but also the hacker.

Encoding of SQL statement often predefined in risky style as below :

Select * from employee where eid = ‘?’

Hacker is capable to replace ? by any SQL command he like. The basic idea is hit
the hole of SQL server that returns all records when statement is true.

Further flaw of SQL statement is injection of additional command followed by semi-


colon.

Next, we will show you how injection happened and avoidance blocks this kind of
vulnerability.

Page 30 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3. Vulnerability Test in WebGoat

4.3.1. Blind SQL Injection

This function ask user to input account number and perform validation after press
submit button.

HTML coding for this function like this :

Enter your Account Number: <input name='account_number' type='TEXT'>


<input name='SUBMIT' type='SUBMIT' value='Go!'>

SQL statement coding for this function like this :

SELECT * FROM user_data WHERE userid = accountNumber

For example, inputted account number = 101 then message “Account number is
valid” prompt since it is correct. Otherwise, “Invalid account number” will prompt if
it is incorrect or “An error occurred, please try again” show if mismatch data type or
field length.

Page 31 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

System will execute appropriated operation if user input account number as normal
as human being. Hacker want to find the value of the attribute “first_name” in table
“user_data” for “userid” equal to “15613”. He appends SQL statement to account
number 101 as below :

101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=15613) ,


1 , 1) ) < 74 )

The execution of submitted SQL command performs as usual. Because there is no


field length control in HTML and syntax of SQL statement is correct become like
this :

SELECT * FROM user_data WHERE userid = 101 {condition 1}


AND
(asc( mid((SELECT first_name FROM user_data WHERE userid=15613) , 1 , 1) ) <
74 ) {condition 2}

System will return true (“Account number is valid”) if first and second conditions are
both true. The returned result provides a hit (“Invalid account number”) to attacker
that first character of name in term of decimal value must greater than 74. Then he
can try next decimal value like 75. He knows the right value when system prompts
below message.

Page 32 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Finally, attack can find out “first_name” through try an error method of one by one
character. The value of “first_name” in table “user_data” for “user_id” equal to
“15613” is Joseph

4.3.2. Numeric SQL Injection

This function asks user to select station from combo box list in order to inquiry the
weather.

Page 33 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

HTML coding for this function like this :

Select your local weather station: <select name='station'>


<option value='101'>
Columbia
</option>
<option value='102'>
Seattle
</option>
<option value='103'>
New York
</option>
<option value='104'>
Houston
</option>
</select><p><input name='SUBMIT' type='SUBMIT' value='Go!'>

SQL statement for this function like this :

SELECT * FROM weather_data WHERE station = ?

In this case, the required information is forced to choose from provided list. It
seems a safety function since no way to append any SQL statement. There is a tool
that can pick up HTTP request between client and web server. Then insert, modify
or delete it before send to server.

For example, hacker select station is Columbia and submit request. Below is caught
message from client to server.

Page 34 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Next, he can modify the value of station form 101 to 101 or 1=1 and submit to web
server.

Web server will respond client base on below SQL statement :

SELECT * FROM weather_data WHERE station = 101 {condition 1}


OR
1=1 {condition 2}

Finally, attacker gets weather information for all station at same time. Because
condition 2 is always true.

Page 35 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3.3. Log Spoofing

This function ask user to input user name and corresponding password for login
purpose.

The coding for file logging like this :

Login failed for username : ‘?’ Or Login succeed for username : ‘?’

The most easily and simple way to hack the log is append with spoofing message. It
mixed Unicode in term of hexadecimal value and expected message. Unicode is
standard universal character set so system will recognize it and show appropriate
character.

Hacker mix Unicode with desired message when login as below :

Smith%0d%0aLogin Succeeded for username: admin

The “%” is a designator to indicate Unicode character set should be invoked in next
two bytes. Unicode “0d” (0x0D) and “0a” (0x0A) refer to control character about
carrier return and line feed respectively.

Page 36 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

As mentioned before, hacker can input any expected message since no field length
control in HTML. The string register to log file as below :

Login failed for username : Smith


Login Succeeded for username: admin

Below figure illustrate spoofed log after insert Unicode and desired message.

Page 37 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3.4. XPATH Injection

This function ask user to input user name and corresponding password in order to
log in employee intranet.

This function required string attribute so query statement similar like this :

SELECT * FROM employee WHERE user_name = ‘?’ {condition 1}


AND
Password = ‘?’ {condition 2}

The syntax of XPATH query is almost the similar as SQL. We can apply same
technique in numeric SQL injection to hack it.

Page 38 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Web server will respond client base on SQL statement as below :

SELECT * FROM employee WHERE user_name = ‘Smith’ OR 1 = 1 {condition 1}


OR
‘a’ = ‘a’ AND Password = ‘******’ {condition 2}

Since 1 = 1 and ‘a’ = ‘a’ are always true, all records in system will display
successfully. (where ****** is any character)

Page 39 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3.5. String SQL Injection

This function asks user to input family name in order to search credit card numbers.

SQL statement of this function as below :

SELECT * FROM user_data WHERE last_name = ‘?’

Apply same hacking method that appends SQL statement when input last name.

Web server will respond client base on SQL statement as below :

SELECT * FROM user_data WHERE last_name = ‘smith’ {condition 1}


OR
‘1’ = ‘1’ {condition 2}

Page 40 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

System will return all credit card records since ‘1’ = ‘1’ is always true.

Page 41 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.3.6. Database Backdoors

This function asks user to input user ID to query employee information.

Pervious testing demonstrates how to perform SQL injection through appending


statement. Actually, hacker is able to insert addition SQL statement by semi-colon
as below :

101; update employee set salary=100000

Page 42 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Web server will responds client base on SQL statement as below :

SELECT userid, password, ssn, salary FROM employee


WHERE userid = 101; {statement 1}
UPDATE employee SET salary=100000 {statement 2}

Similarly, we also can execute a complex SQL command as below :

101; {statement 1}
CREATE TRIGGER myBackDoor BEFORE INSERT ON customers FOR EACH ROW
BEGIN UPDATE customers SET email='john@hackme.com'
WHERE userid = NEW.userid {statement 2}

Page 43 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.4. Avoidance of Vulnerability

4.4.1. HTML

Enhance the HTML coding special for length control. Each input field only offers
enough length of field to user for data input. Assume maximum length of account
number is 20. The recommend HTML coding as follows :

<TD>Account Number</TD>
<TD><INPUT TYPE="TEXT" NAME="accountNo" SIZE="21"
MAXLENGTH="20"></TD>

Actually, it is not a good way by adding control about field length. Because attacker
is able to copy part of HTML coding. Then he pastes it to his own HTML form that
without field length control. This way attacker will avoid the field length checking in
client side.

4.4.2. Java Script

One of preliminary checking method inserts in HTML to provide initial checking base
on some simple logic. We already discovered a lot of malicious values in blacklist
about SQL injection attack. Insert this blacklist into Java script to setup initial
protection as below :

if (document.form.accountNo.value.indexOf("*") >= 0){


alert ("Account Number : \r” + “Cannot input symbol like ‘ * ; %”)
}

Similarly, this way also can attack through modification of Java script. Then skip the
Java script checking in front end.

Page 44 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.4.3. Java Servlet

Introduced method HTML and Java script perform checking in client side. These are
able to adjusted and controlled by hacker. Also, powerful tool like WebScarab that
allow us to insert malicious request before submit. We have to find a channel that
achieves this guarding totally.

Java Servlet implements java programming but this engine is staying in web server.
It will invoke once client submit a request. This checking performs in server side.
Changed request from front end or through a tool both will be detected.

4.4.4. Access Rights of SQL Server

The better way is control access rights in SQL server by different roles such as
query and edit.

Page 45 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Each role is able to divide into manipulate action like a select, insert, update, delete
and execute for individual table. Assess rights can further control by different
columns.

Server will process checking of assess rights when user submit a request. System
permits request and execute the command if authentication is successful. Otherwise,
error prompts as below.

Page 46 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.5. Implementation

Prototype of web application is prepared to demonstrate the proposed idea. This


application is e-phone book that implements idea of first there suggested items
(HTML, Java Scrip and Java Servlet). The environment listed below.

4.5.1. Web Server

UNIX (department of Computing, The Hong Kong Polytechnic University)

4.5.2. Database

Oracle9i Enterprise Edition Release 9.2.0.1.0

4.5.3. Programming Language

a. HTML

b. Java Script

c. Java (TM) 2 Development Kit Standard Edition 1.4.2

4.5.4. Website

http://www.comp.polyu.edu.hk/~05716341t/

Page 47 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.6. Evaluation

This checking will show how back end checking against malicious command is
effective.

4.6.1. Vulnerability via Web Browser

Hacker input symbols {%, *, ‘ , ;} and submit request via HTTP.

Web server return error message after checking by Java Servlet.

Java Servlet is capable to protect malicious command that input by client.

Page 48 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4.6.2. Vulnerability via Tools

Hacker input normal information and submit the request via HTTP.
.

Hacker pickup the HTTP request by tools and append malicious wordings such as
update, insert, delete and set. Then send to web server as normal.

Web server return error message after checking by Java Servlet.

Java Servlet is capable to protect malicious command that input by tool.

Page 49 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5. AJAX Security (by Pierre Yves)

5.1. Background

AJAX (Asynchronous JavaScript And XML) is an emerging technology for web-pages,


based on various technologies such as XHTML, XML, JSON, Javascript and DOM. It
allows the exchange of small amounts of data between the server and the client, so
that the client can update a part of the page without having to reload it. This
increases the speed and usability of the web pages.

Synchronous Asynchronous
Communication Communication

Request
Request
HTML page
HTML page

actio
actio

http Request
XMLHttpRequest
HTML page
XML/JSON data

client serveur client serveur

Page 50 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

AJAX is getting more and more popular and helped create some rich web-based
applications.

To help understand the problems, we will first explain shortly different aspects of
the technologies used by AJAX:

5.1.1. DOM (Document Object Model)

It is a platform and language independent model used to represent the elements of


a XML or (X)HTML document. Each element of the document is a DOM node and all
the nodes are linked together in a tree. Thanks to DOM, any element of a webpage
can be accessed by Javascript code to update it on the client side.

5.1.2. XML

XML is a markup language used by many applications. In AJAX, XML is used to send
data from the server. The data can then be freely manipulated by the client. For
example, if the user clicks on a menu item, a XMLHttpRequest will be sent by the
client to the server, asking for the items of the subsection. The server will send XML
data where each item of the subsection. Javascript code in the webpage will handle
the XML data to create the submenu.

5.1.3. JSON

JSON is an alternative to XML to exchange structured data between the client and
the server.

5.1.4. Javascript

Javascript is used in the HTML so that the client can process data without having to
connect to the server each time. Each action made on the website triggers a
Javascript function, which runs on the client. If needed, the javascript function will
connect to the server and use XMLHttpRequest to request some XML or JSON data,
and will then update the page with this data.

Page 51 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.2. Problem Domain

As every web technology, the technologies used by AJAX have some security
weaknesses.

First of all, in AJAX a lot of processing is done on the client side, through Javascript
function. These functions are inserted in the webpage (or in an external file,
accessible to the client), so the user can read, modify and execute them easily.

Secondly, all the XML/JSON data sent by the server is available to the client. It can
easily be modified.

If all the processing is done through AJAX, this means that the client has control
over everything : the processing and the data received from the server.

5.3. Vulnerability Test in WebGoat

Here are some examples of the attacks that can be done on AJAX websites.

5.3.1. DOM Injection

Sometimes, the server can send data that will be used by the client to update the
DOM. The attacker can intercept this data and inject some javascript code inside it
to manipulate the DOM as he’d like.

For example we have the following page:

Page 52 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

Each time the user enters something in the license key field, the content of the field
is sent to the server for checking. If the license key is correct, the activate button is
activated.
The goal of the attack is to be able to click the activate button without a valid
license key.

The first step is to understand what’s happening when the user enters something in
the license key field. If we look up this field in the source code, we find:

<input onkeyup='validate();' value='' name='key' type='TEXT'>

onkeyup=’validate();’ means that everytime the user enters a key, the field calls the
validate() javascript function. Let’s take a look at this function:

function validate() {
var keyField = document.getElementById('key');
}

Here, we notice a bug in this WebGoat page: the keyfield variable is supposed to
get the content of the key field. It uses the javascript getElementById function to
do so. The problem is that the key field doesn’t have any id but a name. Most
browser won’t be able to process this javascript correctly, so entering a key won’t
do anything. We have to modify the HTML code and add the id attribute to the key
field.

<input onkeyup='validate();' value='' id='key' name='key' type='TEXT'>

With this modification, the validate function can work.

var url = '/WebGoat/attack?Screen=29&menu=1150&from=ajax&key=' +


encodeURIComponent(keyField.value);

Page 53 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

The function inserts the value of the keyfield as a parameter of a GET request.

if (typeof XMLHttpRequest != 'undefined') {


req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject('Microsoft.XMLHTTP');
}

A XMLHttpRequest req is created (it also supports Microsoft’s XMLHTTP for IE


browser)

req.open('GET', url, true);


req.onreadystatechange = callback;
req.send(null);
}

The request is a GET request with the url previously defined. When the state of the
request change, it calls the callback(); function.

function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = req.responseText;
eval(message);
}
}
}

Page 54 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

This function checks if the request is completed, and if its status is 200 (OK). In
that case, it gets the text from the message and use the eval function, which means
that it executes the message as if it was a javascript code.

We use Webscarab to intercept the message sent back by the server. We replace it
with:

document.forms[0].SUBMIT.disabled = false;

This way, the eval function will execute this code and activate the field.

When we get back to the page, the activate button is now enabled.

Of course, the attack could have been made more easily: it would have been
possible to remove the “disable” attribute of the submit button, or to use javascript
to submit the page directly without having to click on any button. But the aim of
this lesson was to show that the DOM can be accessed really easily, especially when
used in conjunction with the eval method, allowing the attacker to manipulate any
part of the page.

Page 55 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.3.2. XML/JSON Injection

If the data is sent with XML or JSON, the XML or JSON code can easily be
intercepted and modified by the client.

XML:
For example, we have the following page:

If we type in our account ID, we’re supposed to have the list of the available items
appear between the account ID field and the submit button. Once again, the
javascript code has some bugs and require some changes to work on all browsers.
First, we had to add the id attribute to the accountID field (to allow the use of the
getElementbyId(accountID) method). Then we had to change the function that
prints the list of the rewards to prevent some exception errors:

strHTML = strHTML + '<tr><td><input name="check' + (i+1001) +'"


type="checkbox"></td><td>';
strHTML = strHTML + node.childNodes[0].nodeValue + '</td></tr>';

Page 56 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

was replaced with:

if (node.childNodes[0] != null) {
strHTML = strHTML + '<tr><td><input name="check' + (i+1001) +'"
type="checkbox"></td><td>';
strHTML = strHTML + node.childNodes[0].nodeValue + '</td></tr>';
}

This way, we are able to have the page work as expected:

The problem is, we want to have access to the Laptop and the Hawaii Cruise. To do
so, we first check what happens exactly when the user enters his account ID:

<input onkeyup='getRewards();' value='' id='accountID' name='accountID'


type='TEXT'>

Page 57 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

So the getRewards() function is called when the user enters something inside the
account ID field. Let’s take a look at this function:

function getRewards() {
var accountIDField = document.getElementById('accountID');
if (accountIDField.value.length < 6 ) {
return;
}
var url = '/WebGoat/attack?Screen=72&menu=1150&from=ajax&accountID='
+ encodeURIComponent(accountIDField.value);

The function first gets the accountID and checks if it’s long enough. If it is, it
creates a URL variable to create a GET request with the accountID field included.

if (typeof XMLHttpRequest != 'undefined') {


req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject('Microsoft.XMLHTTP');
}
req.open('GET', url, true);
req.onreadystatechange = callback;
req.send(null);

It then creates a XMLHttpRequest and sends the get request. The callback function
is called whenever the request’s state changes.

function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var rewards = req.responseXML.getElementsByTagName('root')[0];

Page 58 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

That is all we need to know : the callback function makes sure the request is
complete and OK, and gets the rewards from the response, which seems to be
encoded in XML. The rest of the callback function deals with formatting the data to
print the reward selection form. So all we need to do is intercept the XML message
and add whatever we want inside it.

With Webscarab, we can easily capture the XML data:

We add the rewards we want:

Page 59 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

And we get the following page:

We can now select the Laptop and the Hawaii Cruise.

Page 60 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.3.3. JSON Injection

JSON suffers from the exact same vulnerability. For example, we’ve got the
following webpage:

When we fill the From and To fields, the page updates itself:

If we take a look at the source of the webpage, we see the following:

<input onkeyup='getFlights();' value='' name='travelFrom' type='TEXT'>


<input onkeyup='getFlights();' value='' name='travelTo' type='TEXT'>

Let’s take a look at the getFlights() function that is called each time the user enters
something in each one of this fields :

Page 61 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

function getFlights() {
var fromField = document.getElementById('travelFrom');
if (fromField.value.length < 3 ) { return; }
var toField = document.getElementById('travelTo');
if (toField.value.length < 3 ) { return; }
var url = '/WebGoat/attack?Screen=33&menu=1150&from=ajax&travelFrom=' +
encodeURIComponent(fromField.value) +'&travelTo=' + encodeURIComponent(toField.value);
if (typeof XMLHttpRequest != 'undefined') {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject('Microsoft.XMLHTTP');
}
req.open('GET', url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var card = eval('(' + req.responseText + ')');
var flightsDiv = document.getElementById('flightsDiv');
flightsDiv.innerHTML = '';
var strHTML='';
strHTML = '<tr><td>&nbsp;</td><td>No of Stops</td>';
strHTML = strHTML + '<td>Stops</td><td>Prices</td></tr>';
for(var i=0; i<card.flights.length; i++){
var node = card.flights[i];
strHTML = strHTML + '<tr><td><input name="radio' + i +'"
type="radio"></td><td>';
strHTML = strHTML + card.flights[i].stops + '</td><td>';
strHTML = strHTML + card.flights[i].transit + '</td><td>';
strHTML = strHTML + '<div name="priceID'+i+'" id="priceID'+i+'">' +
card.flights[i].price + '</div></td></tr>';
}
strHTML = '<table border="1">' + strHTML + '</table>';
flightsDiv.innerHTML = strHTML;
}}}

Page 62 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

As we can see, these function use the same methods as in the previous case: the
request is put inside a XMLHttpRequest which is sent to the server. The callback
function then uses the reply to update the page. Here, the reply isn’t XML data but
JSON data.

We use WebScarab to intercept this data:

JSON is a human readable format. We can change any data inside this reply. For
example, we lower the price of the non-stop flight to $300:

The updated page now looks like this:

This way, we can get the non stop-flight for $300.

Page 63 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.3.4. Silent Transaction

AJAX relies heavily on Javascript to process commands on the client side to limit the
load on the server side and allow a faster response on the client side. Some web
browser can execute one of the Javascript function of a webpage by entering

“javascript:function_name(parameter_one,parameter_two,…,parameter_n);” in the
address bar. By inserting such address inside a link, the attacker can force the user
to execute the javascript function, without the user knowing it.

For example, we have the transfer page of a banking application

The user has to press a Confirm button to confirm the transfer. Let’s take a look at
the source code:

<input onClick='processData();' value='Confirm' name='confirm' type='BUTTON'>

This button triggers the processData function. We take a look at the source code of
this function:

Page 64 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

function processData(){

It starts with simple verification of the entered data:

var accountNo = document.getElementById('newAccount').value;


var amount = document.getElementById('amount').value;
if ( accountNo == ''){
alert('Please enter a valid account number to transfer to.')
return;
}
else if ( amount == ''){
alert('Please enter a valid amount to transfer.')
return;
}
var balanceValue = document.getElementById('balanceID').innerText;
balanceValue = balanceValue.replace( new RegExp('$') , '');
if ( parseFloat(amount) > parseFloat(balanceValue) ) {
alert('You can not transfer more funds than what is available in your
balance.')
return;
}

If the data passed all the checks, the transfer happens:

document.getElementById('confirm').value = 'Transferring'
submitData(accountNo, amount);
Then the values are adjusted to reflect the changes:

document.getElementById('confirm').value = 'Confirm'
balanceValue = parseFloat(balanceValue) - parseFloat(amount);
balanceValue = balanceValue.toFixed(2);
document.getElementById('balanceID').innerText = balanceValue + '$';
}

Page 65 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

The actual transfer is handled by the submitData function. If we can trigger this
function without needing the user to click on the button, we could execute a
transfer without the user knowing about it. Furthermore, the transfer would not be
checked by processData function.

If we enter:

javascript:submitData(12345 , 30000);

in the address field of the browser. This will execute the submitData function,
transferring $30000 to account n°12345 without any confirmation on the user part
and any check.

5.4. Avoidance of Vulnerability

All these security holes show that AJAX isn’t a secure web technology. In some
cases, AJAX doesn’t bring anything new compared to classic asynchronous
client/server communications. In these cases, not using AJAX wouldn’t be a problem
for the user and would limit the risks. For example, authentication and other
sensitive data processing can be done by the server through classical and more
secure technologies and AJAX used for everything else (user interface, non-sensitive
data processing…).
But sometimes, not using AJAX will degrade the user experience. In these cases,
other solutions have to be used.

As we’ve seen, the AJAX attacks are possible because the user can tamper with the
data received from the server. This means that there are two main ways to prevent
these attacks. The first one is preventing the user from editing the data and the
second one is detecting when the user has tampered with the data.

Page 66 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

5.4.1. Preventing the user from editing data

To prevent the user from editing the data, we can either try to protect the data or
try to make it so that the user won’t be able to know how to modify it to reach his
goal.

a. Protecting the data

In the DOM: As seen in the previous section, there are no ways to protect the
DOM. The code of the webpage is available to the user and the DOM is inside it
in a human-readable format. That’s why the developer should avoid considering
it as a secure storage area for AJAX applications. No sensitive data should ever
be included in the DOM.

In XML/JSON: Not much can be done to prevent the user from modifying the
XML/JSON data he receives. Encryption cannot help, as decryption will have to
occur on the client side, so the user can access the decryption method and
decrypt the incoming message. A solution could be to obfuscate the data, so
that the attacker will have a hard time understanding how the webpage works,
but this requires a lot of code and makes programming and debugging more
difficult. Besides, HTML isn’t really prone to obfuscation.

As we can see, protecting the data isn’t an option. The client has to be able to
deal with the data and the output has to be a HTML page, which is written in a
human-readable language. Because of this, no data can be protected from the
user. That’s why a more reasonable approach is to limit the amount of sensitive
data sent to the client.

b. Limiting the possibilities of the attacker

Javascript code:

To prevent Silent Transaction attacks, it is important to add checks inside the


javascript code. For example whether the user is identified (if needed), that he
has the privilege to execute this function and that the parameters values are
correct. Adding a confirmation dialog inside the javascript function is also a good
way to make sure that the user is aware of the execution of the function. All
these checks can be bypassed easily by an attacker, but in the context of a
Silent Transaction attack, the user uses the standard version of the webpage
and doesn’t use any hacking tools, so this is of no concern in that case.

Page 67 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

DOM:

DOM shouldn’t hold any sensitive data. This data should stay inside the server
and only be sent when the user can see and edit them without causing any
security trouble. For example, rather than sending the user id, that an attacker
would be able to modify to impersonate another user, it is better to send a
random number that, on the server side, will be linked to the user id. This way,
the attacker won’t know what number to use.

If we take the example mentioned in the previous part, this would mean not
having the submit button on the webpage but sending it when the answer is
correct. In that case, if the button’s name and value aren’t obvious and are
checked by the server upon submission, there is no way the attacker can edit
the incoming data to insert a working button.

XML and JSON messages:

The developer should follow the same advice for data inside XML/JSON reply
that for data inside the DOM. But sometimes, it is necessary to send sensitive
data. In the examples shown in the previous section, the list of items and the
prices of the flight have to be sent. In these cases, the best solution is simply to
consider that these messages can be intercepted and edited and to design
security procedures that take this into account. If the items in the list are sent
with a unique and random ID to identify them, the attacker won’t be able to
figure out the number ID for the items he adds. But for these to have any effect,
the server has to check the ID of the items upon reception.

Preventing the user from editing the data can work up to a point, but it is still
necessary to check for attack attempts to offer full protection.

5.4.2. Detecting attacks attempts

It is of course, useless to attempt to detect attacks on the client side, as the


attacker will be able to bypass the checks done on his computer. This means that
all the checks have to be done on the server side, based on data sent by the client.

As usual in website security, all data sent by the client should be considered as
unsafe. The data can be sent by someone else than the supposed user and by
something else than the regular webpage, so neither the data nor the identity of
the sender can be certified as legitimate without any checks on the server side.

Page 68 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

First, it’s good to check if the sender is the expected one. This can prevent some
attacks, including Silent Transaction attacks. It can be done by checking the referrer
to make sure that the data comes from the page it should come from. Checking the
user-agent might also help making sure that the request is issued by the user’s
browser. But these are not enough, as both can be easily spoofed. Using POST
rather than GET is also useful, as POST requests are harder to fake than GET
requests, and less prone to phishing attacks. The server should also make sure that
the data is sent through POST rather than GET or any other way. Finally, one of the
best ways to prevent spoofing of incoming messages is to implement a sequence
number in the messages, with the server sending the next expected sequence
number to the client by inserting it in a hidden field or in some HTTP field. This is
still vulnerable to man-in-the-middle attacks, but these are more already more
difficult to achieve than regular attacks.

Then, the server has to check the data itself. First, it should prevent Injection
attacks (code or SQL for example) by making the received data not parseable, this
can be done differently, depending on the language used to process the data. Then
it should check if the result has the expected format (number, letters, e-mail
address…) and if it is consistent (a price can not be negative, a meeting can’t be set
prior to today, a non-admin user can’t access to the admin section…). Also it can be
useful to have the client send just an id number, which could be looked up into the
database rather than all the data. In the flights search example, if each flight came
along with a unique id number that referred to the flight in the database, then the
modification of the price by the attacker would not lead to anything: the server
would get the id number, check in the database and get the price information
directly in the database. But in that case, the developer has to be careful not to use
id number that can be guessed. In the rewards example, if each reward is
associated with a simple id such as 1, 2, 3, 4… it would be easy for the attacker to
guess the id number of the reward he wants. In that case, the id number should be
randomly generated to avoid such attacks.

By checking the data on the server side, most AJAX attacks can be detected and
successfully prevented. Even if AJAX is decentralised and rich-client oriented,
sensitive data has to be stored and processed on the server-side to make an AJAX
application secure.

Page 69 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

6. Conclusion

After we did all the related tests on the WebGoat, we found we had learnt a lot of
things on breaking web security. We also learnt how to use other tools to realize
the attack e.g. using WebScarab to rewrite URL.

The experiment enriches us with useful knowledge in information technology career


either we are in programming, system engineering/administration, and security
auditing field.

In addition, this security-training project, WebGoat, can be a part of a security


project on penetration test. The tools & techniques that we learnt can be used to
perform penetration test on a real system.

Finally, we would like to thank Dr. Rocky Chang that he introduced this project to us
and help us to understand web security importance.

Page 70 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

7. Reference

7.1. Book

[1] JAVA HOW TO PROGRAM, Fourth Edition, Deitel & Deitel, Prentice Hall

[2] JavaScript Unleashed, 3rd edition, Richard Wagner and R. Allen Wyke, SAMS

[3] Special Edition Using HTML 4, Sixth Edition, Molly E. Holzschlag, QUE

[4] The Microsoft SQL server 2000 programming step by step, Train, OLAP.,
Redmond, Wash. : Microsoft Press, c2000.

7.2. Web Site

[5] OWASP WebGoat Project


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

[6] Data theft scam targets Google ads


http://www.msnbc.msn.com/id/18348120/

[7] OWASP WebScarab Project


http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project

[8] OWASP Testing Project


http://www.owasp.org/index.php/Category:OWASP_Testing_Project

[9] Wikipedia, the free encyclopedia


http://en.wikipedia.org/wiki/Main_Page

Page 71 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

8. Appendix

8.1. Source Code File List

There are one table structure file, one sequence file, four html and four java files
which named as below :

a. address.txt

b. sequence.txt

c. index.html

d. insertscript.html

e. insertservlet.html

f. view.html

g. insertInfo.java

h. insertScript.java

i. insertServlet.java

j. listAll.java

Page 72 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

8.2. Oracle Table Structure

1. address.txt

insert table address (


address_no varchar2(100),
firstname varchar2(20),
lastname varchar2(20),
sex varchar2(1),
dobd number(2),
dobm number(2),
doby number(4),
mail varchar2(255),
phone varchar2(20),
email varchar2(20),
)

2. sequence.txt

create sequence address_no (


increment by 1
start with 1
maxvalue 100
nocache
nocycle
)

Page 73 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

8.3. HTML with Java Script

1. index.html

<HTML>

<HEAD>
<TITLE>My Phone Book</TITLE>
</HEAD>

<BODY>
<h2>Phone Book Main Menu</h2>
<BR><BR>
<A HREF="insertscript.html">New Contacts - Clinet side checking by Java Script</A>
<BR><BR>
<A HREF="insertservlet.html">New Contacts - Server side checking by Java Servlet</A>
<BR><BR>
<A HREF="view.html">View Phone Book</A>
</BODY>

</HTML>

2. insertscript.html

<HTML>

<HEAD>
<TITLE>Insert New Contact</TITLE>

<script type="text/javascript" language="JavaScript">

var checkFirstName = true


var checkLastName = true
var checkPhoneNo = true

var message1 = "Can not input symbol % * ' ;"


var message2 = "Can not input special wording as 'update', 'insert', 'delete', 'set'"

function doSubmit(){
doCheck()

return (checkFirstName && checkLastName && checkPhoneNo)


}

Page 74 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

function doCheck() {

if (document.insert.firstName.value ==''){
alert ('Please input First Name')
checkFirstName = false
}
else {
if (document.insert.firstName.value.indexOf("%") >= 0){
alert ("First Name :\r" + message1 )
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("*") >= 0){
alert ("First Name :\r" + message1)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf(";") >= 0){
alert ("First Name :\r" + message1)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("'") >= 0){
alert ("First Name :\r" + message1)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("update") >= 0){
alert ("First Name :\r" + message2)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("insert") >= 0){
alert ("First Name :\r" + message2)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("delete") >= 0){
alert ("First Name :\r" + message2)
checkFirstName = false
}
else if (document.insert.firstName.value.indexOf("set") >= 0){
alert ("First Name :\r" + message2)
checkFirstName = false
}
else
checkFirstName = true
}

if (checkFirstName == true){
if (document.insert.lastName.value ==''){
alert ('Please input Last Name')
checkLastName = false
}
else {
if (document.insert.lastName.value.indexOf("%") >= 0){
alert ("Last Name : \r" + message1)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("*") >= 0){

Page 75 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

alert ("Last Name : \r" + message1)


checkLastName = false
}
else if (document.insert.lastName.value.indexOf(";") >= 0){
alert ("Last Name : \r" + message1)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("'") >= 0){
alert ("Last Name : \r" + message1)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("update") >= 0){
alert ("Last Name : \r" + message2)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("insert") >= 0){
alert ("Last Name : \r" + message2)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("delete") >= 0){
alert ("Last Name : \r" + message2)
checkLastName = false
}
else if (document.insert.lastName.value.indexOf("set") >= 0){
alert ("Last Name : \r" + message2)
checkLastName = false
}
else
checkLastName = true
}
}

if (checkFirstName == true && checkLastName == true){


if(document.insert.phoneNo.value ==''){
alert ('Please input Phone Number')
checkPhoneNo = false
}
else {
if (document.insert.phoneNo.value.indexOf("%") >= 0){
alert ("Phone Number : \r" + message1)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf("*") >= 0){
alert ("Phone Number : \r" + message1)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf(";") >= 0){
alert ("Phone Number : \r" + message1)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf("'") >= 0){
alert ("Phone Number : \r" + message1)
checkPhoneNo = false

Page 76 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

}
else if (document.insert.phoneNo.value.indexOf("update") >= 0){
alert ("Phone Number : \r" + message2)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf("insert") >= 0){
alert ("Phone Number : \r" + message2)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf("delete") >= 0){
alert ("Phone Number : \r" + message2)
checkPhoneNo = false
}
else if (document.insert.phoneNo.value.indexOf("set") >= 0){
alert ("Phone Number : \r" + message2)
checkPhoneNo = false
}
else
checkPhoneNo = true
}
}
}

</script>

</HEAD>

<BODY>
<H2>Insert New Contact</H2>

<FORM NAME="insert"
ACTION="http://www2.comp.polyu.edu.hk:8080/~05716341t/servlet/insertScript" METHOD="GET"
onSubmit="return doSubmit()">

<b>Personal Information</b>
<Table CELLSPACING="0" WIDTH="470">
<TR>
<TD>First Name</TD>
<TD><INPUT TYPE="TEXT" NAME="firstName" SIZE="21" MAXLENGTH="20"</TD>
</TR>

<TR>
<TD>Last Name</TD>
<TD><INPUT TYPE="TEXT" NAME="lastName" SIZE="21" MAXLENGTH="20"></TD>
</TR>

<TR>
<TD>Sex</TD>

Page 77 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

<TD>
<SELECT NAME="sex">
<OPTION>M
<OPTION>F
</SELECT>
</TD>
</TR>

<TR>
<TD>Phone Number</TD>
<TD><INPUT TYPE="TEXT" NAME="phoneNo" SIZE="21" MAXLENGTH="20"></TD>
</TR>

<tr><td></td></tr><tr><td></td></tr>

<tr>
<td>
<INPUT TYPE="submit" VALUE="submit" onClick=doSave()>
<INPUT TYPE="RESET" VALUE="reset">
</td>
</tr>

<tr><td><br></td></tr>
<tr><td><A HREF="view.html">View Phone Book</a></td></tr>

<TR>
</table>

</FORM>
</BODY>
</HTML>

3. insertservlet.html

<HTML>

<HEAD>
<TITLE>Insert New Contact</TITLE>
</HEAD>

<BODY>
<H2>Insert New Contact</H2>

<FORM ACTION="http://www2.comp.polyu.edu.hk:8080/~05716341t/servlet/insertServlet"
METHOD="GET">

<b>Personal Information</b>

Page 78 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

<Table CELLSPACING="0" WIDTH="470">


<TR>
<TD>First Name</TD>
<TD><INPUT TYPE="TEXT" NAME="firstName" SIZE="21" MAXLENGTH="20"></TD>
</TR>

<TR>
<TD>Last Name</TD>
<TD><INPUT TYPE="TEXT" NAME="lastName" SIZE="21" MAXLENGTH="20"></TD>
</TR>

<TR>
<TD>Sex</TD>
<TD> <SELECT NAME="sex">
<OPTION>M
<OPTION>F
</SELECT>
</TR>

<TR>
<TD>Phone Number</TD>
<TD><INPUT TYPE="TEXT" NAME="phoneNo" SIZE="21" MAXLENGTH="20"></TD>
</TR>

<tr><td></td></tr><tr><td></td></tr>

<tr><td>
<INPUT TYPE="SUBMIT" VALUE="submit">
<INPUT TYPE="RESET" VALUE="reset"></td></tr>

<tr><td><br></td></tr>
<tr><td><A HREF="view.html">View Phone Book</a></td></tr>

</table>
</FORM>
</BODY>
</HTML>

Page 79 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

4. view.html

<HTML>

<HEAD>
<TITLE>View Phone Book</TITLE>
</HEAD>

<BODY>
<H2>View Phone Book</H2>

<FORM ACTION="http://www2.comp.polyu.edu.hk:8080/~05716341t/servlet/listAll"
METHOD="GET">

<table>
<tr>
<td>Press "OK" to veiw existing contact record

<td><INPUT TYPE="SUBMIT" VALUE=" OK "></tr>

<tr><td><tr><td><tr><td><tr><td><tr><td><tr><td>
<tr><td><tr><td><tr><td><tr><td><tr><td><tr><td>

<A HREF="insertscript.html">New Contacts - Clinet side checking by Java Script</A>


<BR><BR>
<A HREF="insertservlet.html">New Contacts - Server side checking by Java Servlet</A>
<BR><BR>

</table>
</FORM>
</BODY>
</HTML>

Page 80 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

8.4. Java

1. insertInfo.java

// ********************************************
// INSERT NEW CONTACT TO ADDRESS BOOK
// ********************************************

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class insertInfo extends HttpServlet {

// Use the get command to recall the servlet


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
{
// Set the content type of the response
resp.setContentType("text/html");

// Create a PrintWriter object


java.io.PrintWriter out = new java.io.PrintWriter(resp.getOutputStream());

// Print the header result of HTML


out.println("<html>");
out.println("<head>");
out.println("<title>Insert New Contact</title>");
out.println("</head>");
out.println("<br>");
out.println("<br>");
out.println("<br>");

// Call the insert record procedure


insertRecord("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@studora.comp.polyu.edu.hk:1521:dbms",
"Insert Into address (address_no,firstname,lastname, sex,phone)
Values(address_no.nextval,?,?,?,?)", req, out);

// Close stream
out.println("</html>");
out.flush();
out.close();
}

// Execute insert record procedure


private boolean insertRecord(String driverName,

Page 81 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

String connectionURL,
String insertstate,
HttpServletRequest req,
java.io.PrintWriter out)
{
boolean success = true;

// JDBC Connection
Connection con = null;

// SQL PrameterSet
PreparedStatement ps = null;

try {

// Create an instance of the JDBC driver so that it has a chance to register


itself
Class.forName(driverName).newInstance();

// Create a new database connection.


con = DriverManager.getConnection(connectionURL, "c5716341",
"chersmum");

// Get parameter from HTML


ps = con.prepareStatement(insertstate);
ps.setString(1, req.getParameter("firstName"));
ps.setString(2, req.getParameter("lastName"));
ps.setString(3, req.getParameter("sex"));
ps.setString(4, req.getParameter("phoneNo"));

//Print result message if insert is successful


if (ps.executeUpdate() > 0)
{
out.println("<h2><center>");
out.println("New Contact Insert Successful !");
out.println("</center></h2>");
out.println("<br>");

}
}

//Print result message if invald input for other information


catch (Exception exother) {
out.println("<h2><center>");
out.println("<br>");
out.println("Error !");
out.println("<br>");
out.println(exother);
out.println("</center></h2>");
success = false;
}

Page 82 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

finally {
// Always close properly
try {

if (ps != null)
ps.close();

if (con != null)
con.close();
}

catch (Exception ex) {


// Ignore any errors here
}
}

return success;
}

2. insertScript.java

// ********************************************
// INSERT NEW CONTACT TO ADDRESS BOOK
// ********************************************

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class insertScript extends HttpServlet {

// Use the get command to recall the servlet


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
{
// Set the content type of the response
resp.setContentType("text/html");

// Create a PrintWriter object


java.io.PrintWriter out = new java.io.PrintWriter(resp.getOutputStream());

// Print the header result of HTML


out.println("<html>");
out.println("<head>");

Page 83 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

out.println("<title>Insert New Contact</title>");


out.println("</head>");
out.println("<br>");
out.println("<br>");
out.println("<br>");

// Call the insert record procedure


insertRecord("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@studora.comp.polyu.edu.hk:1521:dbms",
"Insert Into address (address_no,firstname,lastname, sex,phone)
Values(address_no.nextval,?,?,?,?)", req, out);

// Close stream
out.println("</html>");
out.flush();
out.close();
}

// Execute insert record procedure


private boolean insertRecord(String driverName,
String connectionURL,
String insertstate,
HttpServletRequest req,
java.io.PrintWriter out)
{
boolean success = true;

// JDBC Connection
Connection con = null;

// SQL PrameterSet
PreparedStatement ps = null;

try {

// Create an instance of the JDBC driver so that it has a chance to register


itself
Class.forName(driverName).newInstance();

// Create a new database connection.


con = DriverManager.getConnection(connectionURL, "c5716341",
"chersmum");

// Get parameter from HTML


ps = con.prepareStatement(insertstate);
ps.setString(1, req.getParameter("firstName"));
ps.setString(2, req.getParameter("lastName"));
ps.setString(3, req.getParameter("sex"));
ps.setString(4, req.getParameter("phoneNo"));

//Print result message if insert is successful


if (ps.executeUpdate() > 0)

Page 84 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

{
out.println("<h2><center>");
out.println("New Contact Insert Successful !");
out.println("</center></h2>");
out.println("<br>");

}
}

//Print result message if invald input for other information


catch (Exception exother) {
out.println("<h2><center>");
out.println("<br>");
out.println("Error !");
out.println("<br>");
out.println(exother);
out.println("</center></h2>");
success = false;
}

finally {
// Always close properly
try {

if (ps != null)
ps.close();

if (con != null)
con.close();
}

catch (Exception ex) {


// Ignore any errors here
}
}

return success;
}

Page 85 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

insertServlet.java

// ********************************************
// INSERT NEW CONTACT TO ADDRESS BOOK
// ********************************************

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class insertServlet extends HttpServlet {

boolean checkFirstName;
boolean checkLastName;
boolean checkSex;
boolean checkPhoneNo;
boolean valid;

String output;

// Use the get command to recall the servlet


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException {
// Set the content type of the response
resp.setContentType("text/html");

// Create a PrintWriter object


java.io.PrintWriter out = new java.io.PrintWriter(resp.getOutputStream());

// Print the header result of HTML


out.println("<html>");
out.println("<head>");
out.println("<title>Insert New Contact</title>");
out.println("</head>");
out.println("<br>");
out.println("<br>");
out.println("<br>");

// Call the insert record procedure


insertRecord("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@studora.comp.polyu.edu.hk:1521:dbms",
"Insert Into address (address_no,firstname,lastname, sex,phone)
Values(address_no.nextval,?,?,?,?)",
req, out);

// Close stream
out.println("</html>");
out.flush();

Page 86 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

out.close();
}

// Execute insert record procedure


private boolean insertRecord(String driverName,
String connectionURL,
String insertstate,
HttpServletRequest req,
java.io.PrintWriter out){

boolean success = true;

// JDBC Connection
Connection con = null;

// SQL PrameterSet
PreparedStatement ps = null;

try {

// Create an instance of the JDBC driver so that it has a chance to register


itself
Class.forName(driverName).newInstance();

// Create a new database connection.


con = DriverManager.getConnection(connectionURL, "c5716341",
"chersmum");

// Check malious value

doCheck(1, req.getParameter("firstName"),out);
if (!checkFirstName){
out.println("<h2><center>");
out.println(output);
}
else {
doCheck(2, req.getParameter("lastName"),out);
if (!checkLastName){
out.println("<h2><center>");
out.println(output);
}

else{
doCheck(3, req.getParameter("sex"),out);
if (!checkSex){
out.println("<h2><center>");
out.println(output);
}
else{
doCheck(4, req.getParameter("phoneNo"),out);
if (!checkPhoneNo){
out.println("<h2><center>");

Page 87 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

out.println(output);
}
}
}
}

if (checkFirstName && checkLastName && checkSex &&


checkPhoneNo) {

// Get parameter from HTML


ps = con.prepareStatement(insertstate);
ps.setString(1, req.getParameter("firstName"));
ps.setString(2, req.getParameter("lastName"));
ps.setString(3, req.getParameter("sex"));
ps.setString(4, req.getParameter("phoneNo"));

//Print result message if insert is successful


if (ps.executeUpdate() > 0){
out.println("<h2><center>");
out.println("New Contact Insert Successful !");
out.println("</center></h2>");
out.println("<br>");
}
}
}

//Print result message if invald input for other information


catch (Exception exother) {
out.println("<h2><center>");
out.println("<br>");
out.println("Error !");
out.println("<br>");
out.println(exother);
out.println("</center></h2>");
success = false;
}

finally {
// Always close properly
try {

if (ps != null)
ps.close();

if (con != null)
con.close();
}

catch (Exception ex) {


// Ignore any errors here
}

Page 88 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

return success;
}

public void doCheck(int tabNo, String input, java.io.PrintWriter out) {

String message1 = "Can not input symbol % * ' ;";


String message2 = "Can not input special wording as 'update', 'insert', 'delete', 'set'" ;
String tab;

if (tabNo == 1)
tab = "First Name";
else if (tabNo == 2)
tab = "Last Name";
else if (tabNo == 3)
tab = "Sex";
else
tab = "Phone No";

if (input.length() == 0 || input == null){

output = "Please input " + tab + ".";


if (tabNo == 1)
checkFirstName = false;
else if (tabNo == 2)
checkLastName = false;
else if (tabNo == 3)
checkSex = false;
else
checkPhoneNo = false;
}
else {
if (input.indexOf("%") >= 0 || input.indexOf("*") >= 0 ||
input.indexOf(";") >= 0 || input.indexOf("'") >= 0 ){

output = tab + " : " + message1;

if (tabNo == 1)
checkFirstName = false;
else if (tabNo == 2)
checkLastName = false;
else if (tabNo == 3)
checkSex = false;
else
checkPhoneNo = false;

}
else if (input.indexOf("update") >= 0 || input.indexOf("insert") >= 0 ||
input.indexOf("delete") >= 0 || input.indexOf("set") >= 0){

Page 89 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

output = tab + " : " + message2;

if (tabNo == 1)
checkFirstName = false;
else if (tabNo == 2)
checkLastName = false;
else if (tabNo == 3)
checkSex = false;
else
checkPhoneNo = false;

}
else{
checkFirstName = true;
checkLastName = true;
checkSex = true;
checkPhoneNo = true;
}

4. listAll.java

// *****************************************
// LIST ALL EXISTING CONTACT RECORD
// *****************************************

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class listAll extends HttpServlet


{
// Use the get command to recall the servlet
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, java.io.IOException
{
// Set the content type of the response
resp.setContentType("text/html");

// Create a PrintWriter object


java.io.PrintWriter out =

Page 90 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

new java.io.PrintWriter(resp.getOutputStream());

// Print the header result of HTML


out.println("<html>");
out.println("<head>");
out.println("<title>Phone Book</title>");
out.println("</head>");
out.println("<h2><center>");
out.println("Phone Book");
out.println("</center></h2>");
out.println("<br>");

// Call the contact query procedure


contactquery("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@studora.comp.polyu.edu.hk:1521:dbms",
"SELECT * FROM address", out);

// Close stream
out.println("</html>");
out.flush();
out.close();
}

//Execute contact query procedure


private boolean contactquery(String driverName,
String connectionURL,
String querystate,
java.io.PrintWriter out)
{
boolean success = true;

// JDBC Connection
Connection con = null;

// JDBC Statement
Statement stmt = null;

// JDBC ResultSet
ResultSet rs = null;

// Time the query processing time


long startMS = System.currentTimeMillis();

// Keep the number of rows in the ResultSet


int rowCount = 0;

try {
// Create an instance of the JDBC driver so that it has a chance to register
itself
Class.forName(driverName).newInstance();

// Create a new database connection


con = DriverManager.getConnection(connectionURL, "c5716341",
"chersmum");

Page 91 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

// Create a statement object that we can execute queries


stmt = con.createStatement();

// Execute the query


rs = stmt.executeQuery(querystate);

// Format the results into an HTML table


rowCount = formatTable(rs, out);

//Print no. of existing record


out.println("<br>");
out.println("<br>");
out.println("<td>Total record is "+rowCount);
}

catch (SQLException exsql) {


out.println(querystate);
out.println(exsql);
success = false;
}

catch (Exception ex) {


// Print error message
out.println("Exception!");
ex.printStackTrace(out);
success = false;
}

finally {
try {
// Always close properly
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
}
catch (Exception ex) {
// Ignore any errors here
}
}

return success;
}

//Execute table formating


private int formatTable(java.sql.ResultSet rs,
java.io.PrintWriter out)
throws Exception
{
int record = 0;

Page 92 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

// Create the table


out.println("<center><table border>");

// Process the results. First dump out the column


// headers as found in the ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();

int columnCount = rsmd.getColumnCount();

// Start the table row


out.println("<tr>");

// Print record title


for (int i = 0; i < columnCount; i++) {

switch (i+1)
{
case 1 :
out.print("<th>");
out.println("No.");
out.print("</th>");
break;
case 2 :
out.print("<th>");
out.println("First Name");
out.print("</th>");
break;
case 3 :
out.print("<th>");
out.println("Last Name");
out.print("</th>");
break;
case 4 :
out.print("<th>");
out.println("Sex");
out.print("</th>");
break;
case 5 :
out.print("<th>");
out.println("Phone Number");
out.print("</th>");
break;
}
}

// End the table row


out.println("</tr>");

// Now walk through the entire ResultSet and get each row
while (rs.next())
{
record++;

Page 93 of 94
COMP444 – Internet Infrastructure Security – OWASP WebGoat Project

// Start a table row


out.println("<tr>");

// Print detail record


for (int i = 0; i < columnCount; i++) {

switch (i+1)
{
case 1 :
out.print("<td>");
out.print(rs.getString(1));
out.print("</td>");
break;
case 2 :
out.print("<td>");

out.print(rs.getString(2));
out.print("</td>");
break;
case 3 :
out.print("<td>");
out.print(rs.getString(3));
out.print("</td>");
break;
case 4 :
out.print("<td>");
out.print(rs.getString(4));
out.print("</td>");
break;
case 5 :
out.print("<td>");
out.print(rs.getString(9));
out.print("</td>");
break;
}

}
// End the table row
out.println("</tr>");
}

// End the table


out.println("</table></center>");

return record;

}
}

Page 94 of 94

Das könnte Ihnen auch gefallen