0% found this document useful (0 votes)
5 views50 pages

CSE420+Practical+Lab4A+Code+Automation+and+Cross Site+Scripting+ +mozn1079657

The document outlines a practical lab for CSE420 Ethical Hacking, focusing on code automation and cross-site scripting. It includes tasks such as writing a Bash script to automate Nmap scans and modifying the script to enumerate Samba shares. The lab emphasizes the importance of coding skills in penetration testing and provides detailed instructions for creating and testing the script.

Uploaded by

abid.2nice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views50 pages

CSE420+Practical+Lab4A+Code+Automation+and+Cross Site+Scripting+ +mozn1079657

The document outlines a practical lab for CSE420 Ethical Hacking, focusing on code automation and cross-site scripting. It includes tasks such as writing a Bash script to automate Nmap scans and modifying the script to enumerate Samba shares. The lab emphasizes the importance of coding skills in penetration testing and provides detailed instructions for creating and testing the script.

Uploaded by

abid.2nice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Practical Lab4A: Code Automation and Cross-Site Scripting

CSE420- Ethical Hacking (Spring 24-25)


Deadline: Sunday 18th of May 2025 @ 23:59
Mozn Abdulaziz - 1079657

Part 1: Analyze Code Automation


Vulnerability scanning and information gathering can be very time consuming. As you have seen there are
a number of software products available that automate these processes by using multiple tools against
multiple targets. While automated scanners are great and can do a lot for us, sometimes they don’t suit our
specific needs. It is important that you work on your coding skills so that you can understand automation
scripts that are written in a variety of scripting languages. You need to understand existing scripts and be
able to modify them to suit our current needs. You should also know enough scripting to create some of
your own scripts by following examples and consulting online resources and coding forums.

Objectives
In this part, you will complete the following objectives:
• Task 1.1: Write a Bash Script to Automate an Nmap Scan and Store the Results.
• Task 1.2: Differentiate between Scripts Written in Bash, Python, Ruby, and PowerShell.

Background / Scenario
Penetration testing often requires repetitive tasks that use various tools to perform reconnaissance,
analyze, and exploit vulnerable systems. Creating scripts to automate these tasks reduces the time
necessary to complete the penetration testing project.

Required Resources
• Kali VM customized for the Ethical Hacker course

Instructions

Task 1.1: Bash Script to Automate an Nmap Scan and Store the Results.
Step 1.1.1: Create a basic Bash script.
The Bash shell has a built-in script interpreter. Bash scripts can be written in any text editor and require
minimal programming experience. The scripts can then be run from the Bash shell prompt. The syntax and
structure of Bash scripts is similar to what you would type at the command prompt if you were doing the
task manually. In this step, you will write a short script named recon.sh to perform a simple Nmap scan.

CSE420-Practical Lab4A: Code Automation and XSS 1


a. We need first to change the prompt to include the date and time, and your student ID. Run the
command: PS1=”\d \@ [Your_Student-ID]”. Use your own student ID. The prompt will change as
shown below.

b. To begin your first script, log in to Kali, with the username kali and password kali. Open a terminal
window and ping the target host at 10.6.6.23 to ensure that it is available on the network.

┌──(kali㉿Kali)-[~]
└─$ ping -c5 10.6.6.23

PING 10.6.6.23 (10.6.6.23) 56(84) bytes of data.


64 bytes from 10.6.6.23: icmp_seq=1 ttl=64 time=0.229 ms
64 bytes from 10.6.6.23: icmp_seq=2 ttl=64 time=0.048 ms
64 bytes from 10.6.6.23: icmp_seq=3 ttl=64 time=0.060 ms
64 bytes from 10.6.6.23: icmp_seq=4 ttl=64 time=0.054 ms
64 bytes from 10.6.6.23: icmp_seq=5 ttl=64 time=0.038 ms

--- 10.6.6.23 ping statistics ---


5 packets transmitted, 5 received, 0% packet loss, time 5451ms
rtt min/avg/max/mdev = 0.038/0.085/0.229/0.071 ms

In the following screenshot above we are pinging the target host which is (10.6.6.23)

CSE420-Practical Lab4A: Code Automation and XSS 2


c. Open the Mousepad text editor from the Applications menu. (Any text editor can be used to create
the file.) The first line in the Bash script is a special kind of comment line that indicates the location
of the interpreter to be used to run the code. This line is called a "shebang" and is common to most
Linux scripts. Enter the shebang #!/bin/bash on line 1 this identifies the language of the script to
the command interpreter.
Line numbers are added automatically in Mousepad, do not type them. They should not appear in
the script itself.
1 #!/bin/bash

d. In this script, the user will enter the IP address of the target as a command line option. If no option
is entered, the user will receive an error message showing the proper command syntax. Enter the
if/then sequence as shown.
2 # Check if IP of target is entered
3 if [ -z "$1" ]
4 then
5 echo "Correct usage is ./recon.sh <IP>"
6 exit 1
7 else
8 echo "Target IP $1"
9 fi

Here we opened the mousepad command which gave us an empty text editor

CSE420-Practical Lab4A: Code Automation and XSS 3


We then added the given code as shown above in the screenshot
Analyzing script code is an important skill for a penetration tester. Not only will you write automation
code, you will often need to determine what an existing script does. The meaning of each line of is
as follows:
• Line 2 is a comment line that begins with a hash tag #. Lines starting with # are used to
document the script. Comment lines are ignored by the command interpreter.
• Line 3 starts a test to determine if the input option variable $1 exists. By default, Bash scripts
accept command line options into variables numbered by their position in the command. The
-z returns "true" if the value of $1 is null. Bash requires a space after the first bracket [ and a
space before the last bracket ].
• Line 4 indicates what to do if the option variable does not exist (is null). Lines 5 and 6 are
indented to indicate that they are part of the then clause.
• Line 5 prints a message to the screen. Bash uses the echo command to print what is in the
double quotes to the screen.
• Line 6 will cause the script execution to stop and exit to the CLI if the condition is met.
• Line 7 indicates what to do if the if condition is false.
• Line 8 prints a message with the input value that was supplied and stored in the $1 variable.
Note that further work is required to validate that the input was actually a valid IP address.
This is beyond the scope of this lab.
• Line 9 indicates that the if/then clauses are complete.
e. Save your file with the name recon.sh. In this example, the file is saved in the /home/kali directory.

CSE420-Practical Lab4A: Code Automation and XSS 4


Here I saved the file as recon.sh
f. To make a text file into an executable, it is necessary to change the Linux permissions on the file.
Open a terminal window on the Kali desktop. List the directory using ls and verify that your script
file is there and has the correct name. Enter the chmod +x command to add the executable
permission to your file.

┌──(kali㉿Kali)-[~]
└─$ chmod +x recon.sh

Here I ran the following command given


g. Test your script by running it first with the IP address of the target (10.6.6.23) specified.

┌──(kali㉿Kali)-[~]
└─$ ./recon.sh 10.6.6.23
Target IP 10.6.6.23

Here I also ran the given command.


h. Further test your script by running it as follows:
1. with no input supplied after the script name

For this screenshot in order to test the script further we added the above
command using the file name we saved.

CSE420-Practical Lab4A: Code Automation and XSS 5


2. with other text or an invalid IP address supplied after the script name. Note that if you are
entering non-numeric text, it must be surrounded by quotation marks.

For the second test we added a test in the command after we wrote the file
name saved from the previous task, we insured that the text is surrounded on
quotation.

The purpose of the script is to automate Nmap scanning using the target IP address value that is
supplied to the script. What do you think will happen if the value is not a legal IP address?
Answer below and include screenshots.

If the IP address is not legal then most likely the nmap will return an 1
error and terminate the process. Furthermore no action will be taken. In
order to avoid such encounter, the IP address should follow a valid
formatting, and should be valid and legal. [1]

i. Now edit the script file to enter the commands that will run the Nmap scan. Use the variable $1 to
indicate the IP address of the target device you want to scan. The results of the Nmap scan will be
written to a file named scan_results.txt in the current directory.
8 echo "Running Nmap…"
9 # Run Nmap scan on target and save results to file
10 nmap -sV $1 > scan_results.txt
10 echo "Scan complete – results written to scan_results.txt"

CSE420-Practical Lab4A: Code Automation and XSS 6


The edited file after adding the above codes to the previous file we
saved.

What type of Nmap scan will be run with this script?


Answer below and include screenshots.

The nmap scan that will run this script is the version detection scan “- 2
sV”, in which it will determine the information of the version of the open
ports as well as their service. [2]

j. Save the script. Below is the recon.sh script so far.


#!/bin/bash
# Check if IP of target is entered
if [ -z "$1" ]
then
echo "Correct usage is ./recon.sh <IP>"
exit
else
echo "Target IP $1"
echo "Running Nmap…"
# Run Nmap scan on target and save results to file
nmap -sV $1 > scan_results.txt
echo "Scan complete – results written to scan_results.txt"
fi

k. Run it again with the target IP address supplied.

CSE420-Practical Lab4A: Code Automation and XSS 7


┌──(kali㉿kali)-[~]
└─$ ./recon.sh 10.6.6.23
Target IP 10.6.6.23
Running Nmap....
Scan complete -- results written to scan_results.txt

After running the given command


l. Use the cat command to view the contents of the scan_results.txt file that you created with the
script.

CSE420-Practical Lab4A: Code Automation and XSS 8


The two screenshots above show that we used the cat command so we can see the
contents of the scan_results file.
What ports are open on the target?
Answer below and include screenshots.

We found the following ports to be opened based on what was displayed


from the screenshot above:
3
Port Service Version
21/tcp ftp Vsftpd 3.0.3
22/tcp Ssh OpenSSH 7.9p1
53/tcp Domain ISC BIND 9.11.5
80/tcp http Nginx 1.14.2
139/tcp Netbios-ssn Samba smbd 3.x
445/tcp Netbios-ssn Samba smbd 3.x

CSE420-Practical Lab4A: Code Automation and XSS 9


Step 1.1.2: Modify the script to enumerate shares on the target.
As seen in the previous step, the target at 10.6.6.23 has open ports that could indicate a Samba server. In
this step, you will edit your script to run enum4linux if a Samba drive share port is open to determine any
available drive shares or user accounts.
What indicates that a Samba server is running on the hosts?
Answer below and include screenshots.

By the ports, given that it usually runs on ports 139/tcp and 445/tcp as
4
shown in the below screenshot, as well ass when information is displayed
you can see from the version.

a. Open the recon.sh file in the text editor. Add the following commands.
13 # If the Samba port 445 is found and open, run enum4linux.
14 if grep 445 scan_results.txt | grep -iq open
15 then
16 enum4linux -U -S $1 >> scan_results.txt
17 echo "Samba found. Enumeration complete."
18 echo "Results added to scan_results.txt."
19 echo "To view the results, cat the file."
20 else

CSE420-Practical Lab4A: Code Automation and XSS 10


21 echo "Open SMB share ports not found."
22 fi

The following screenshot shows the extra added code based on the code provided above
to the recon.sh file.
b. Analyze the additional code.

• Line 13 is a comment.
• Line 14 indicates the start of an if/then statement that will search in the Nmap results for open
port 445. The grep command searches lines in the file that match the pattern “445 open.” The
grep command searches for lines that match the pattern “445” first. Then the output is piped
into a second grep command to search again for lines that match the pattern open. With the
option -i, the grep command ignores the case distinctions in the search patterns. The option -
q suppresses standard outputs.
• Line 15 is the "then" clause. This contains the command that will be executed should the if test
return "true".
• Lines 16 - 19 are executed if the SMB file sharing port (445) is found. Line 16 runs enum4linux
with the -U and -S options on the target host specified in $1 and appends the results to the end
of the scan_results.txt file. Lines 17, 18 and 19 display messages when emun4linux finished
the scan and provides directions to view the results.
• Line 20 indicates that the action to take if the logical if the condition fails.
• Line 21 displays a message if the SMB file sharing port (445) is not open.
• Line 22 the fi signifies the end of the if/then clause.

What do the -U and -S options do in enum4linux?


Answer below and include screenshots.

5
CSE420-Practical Lab4A: Code Automation and XSS 11
-U which is user enumeration tries to enumerate the users accounts on
the target system while -S “share enumeration” tries to enumerate shared
resources on the target. [3]

c. Save the recon.sh file in the text editor and exit to the command prompt. Below is the complete
recon.sh script.
#!/bin/bash
# Check if IP of target is entered
if [ -z "$1" ]
then
echo "Correct usage is ./recon.sh "
exit
else
echo "Target IP $1"
echo "Running Nmap…"
# Run Nmap scan on target and save results to file
nmap -sV $1 > scan_results.txt
echo "Scan complete – results written to scan_results.txt"
fi
# If the Samba port 445 is found and open, run enum4linux.
if grep 445 scan_results.txt | grep -iq open
then
enum4linux -U -S $1 >> scan_results.txt
echo "Samba found. Enumeration complete."
echo "Results added to scan_results.txt."
echo "To view the results, cat the file."
else
echo "Open SMB share ports not found."
Fi

d. Run the script again on the target system (10.6.6.23).

┌──(kali㉿kali)-[~]
└─$ ./recon.sh 10.6.6.23
Running Nmap....
Scan complete -- results written to scan_results.txt
Samba found. Enumeration complete.
Results added to scan_results.txt.
To view the results, cat the file.

Using the command again as shown above

e. Use the cat command to view the results contained in the scan_results.txt file.

CSE420-Practical Lab4A: Code Automation and XSS 12


CSE420-Practical Lab4A: Code Automation and XSS 13
What file shares were found on the target?

6
Answer below and include screenshots.

We were able to find the following based on the screenshot above:


Homes → all homes directories
Workfiles → Confidential Workfiles
Print$ → Printer Drivers
IPC$ → IPC Service (Samba 4.9.5-Debian)

Step 1.1.3: Automate Nmap from the command line.


Another way to automate Nmap is to scan a group of specific targets that are specified in an external file.
a. Create a new file in Mousepad and type in the IP addresses of the existing hosts on the 10.6.6.0/24
network. To list all the available hosts with their IP addresses, enter the command containers at a
terminal.

CSE420-Practical Lab4A: Code Automation and XSS 14


Be sure the IP addresses are separated with a space or list each IP address on a separate line.
b. Save the file with the name to_scan.txt.
c. At the prompt, enter the command to run Nmap with the targets from the file. For the purposes of
this lab, will just run a simple ping scan, but any type of scan that takes an IP address as a target
can be run in this way.

┌──(kali㉿Kali)-[~]
└─$ nmap -sn -iL to_scan.txt

Saving the file as to_scan

We used the above given command to check the ip addresses that are up.

CSE420-Practical Lab4A: Code Automation and XSS 15


d. After a brief delay, you should see Nmap output the scan reports for each host that was specified
in the to_scan.txt file.
Note: The to_scan.txt file does not require executable permissions because it is serving as a data
file, not as a script file.

Task 2: Differentiate between scripts written in Bash, Python, Ruby,


and PowerShell
In this part, you will use what you learned in the previous part about writing and analyzing a Bash script to
analyze pre-written scripts. Knowing what scripting language is being used in scripts that you discover while
penetration testing enables you to understand the purpose of the script, and potentially be able to modify it
to obtain additional information.
Use this chart that illustrates the different syntax characteristics of the scripting languages.

CSE420-Practical Lab4A: Code Automation and XSS 16


Function Python Bash Ruby PowerShell
Shebang Example – #!/usr/bin/python3 #!/bin/bash #!/usr/local/bin/ruby #!/usr/bin/env pwsh
special comment line at the top Only needed if running PS in Linux, not
of script that identifies the path
to the interpreter required in Windows
Loading Modules import libraryName as alias n/a; Bash does not require loading Require ‘libraryName’ n/a; PowerShell does not require loading
modules modules
from libraryName import Self contained libraries are called ‘gems’
subModule
Defining Variables variableName = variableValue variableName = variableValue variableName = variableValue $varvariableName = varvariableValue

Variables read in as options from CLI Cannot begin with number or capital
are assigned $1, $2, ..., $n letter.
Calling Variables variableName $variableName #variableName $varibleName

Example: Example: Example: Example:


print(varibleName) echo $variableName puts variableName PS C:\> $variableName
Comparison Uses Arithmetic symbols Uses alpha: Uses Arithmetic symbols Uses a variety of operators:
Equal is == Equal to -eq Equal is == Equal to:
Not Equal is != Not equal to -ne Not Equal is != -eq, -ieq, -ceq
Greater Than is > Greater than -gt Greater Than is > Not equal to:
Equal or Greater Than is >= Greater than or equal to -ge Equal or Greater Than is >= -ne, -ine, -cne
Less Than is < Less than -lt Less Than is < Greater than:
Equal or Less Than is <= Less than or equal to -le Equal or Less Than is <= -gt, -igt, -cgt
Greater than or equal to:
Example: -ge, -ige, -cge
$x -gt 8 Less than:
-lt, -ilt, -clt
If using arithmetic symbols, enclose in Less than or equal to:
double parenthesis. -le, -ile, -cle
(($a > $b))
If Conditions if condition1: if [condition1] if condition1 if (condition1) {
action1 then action1 action1 action1
elif condition2: elif [condition2] elsif condition2 }
action2 then action2 action2 elseif (condition2) {
else: else else action2
action3 action3 action3 }
fi end else {
action3
unless can be used if just checking If a }
condition is "not true"
Do while loops Example: Example: Example: Example :
i= 1 x=1 while x >= 1 do {
while i < 6: while [ $x -le 5 ] puts #@x Write-Host $x
print(i) do x=x-1 $x =$ x--
i=I+1 echo "count " $x end } while ($x -ge 1)
print ("All done") x=$(( $x + 1 ))
done

CSE420-Practical Lab4A: Code Automation and XSS 17


a. Review the code sample shown. Use the syntax characteristics to determine which scripting
language is used to interpret the code.
1 import nmap
2 # take the range of ports to
3 # be scanned
4 begin = 21
5 end = 80
6 target = '10.6.6.23'
7 # scan the port range
8 for i in range(begin,end+1):
9 results = nmap.PortScanner(target,str(i))
10 results = results['scan'][target]['tcp'][i]['state']
11 print('Port {i} is {results}.')

In the provided screenshot we have created a new mousepad and added the given code above.
Using the information from the chart, what shebang should be the first line of code?
Answer below.

It should be → #!/usr/bin/python3 7
What port range will be scanned?
Answer below and include screenshots.
Based on the code it will begin at 21 and end at 80, so the range would
be 21-80. 8

CSE420-Practical Lab4A: Code Automation and XSS 18


CSE420-Practical Lab4A: Code Automation and XSS 19
CSE420-Practical Lab4A: Code Automation and XSS 20
b. Review the code sample shown. Use the syntax characteristics to determine which scripting
language is used to interpret the code.
1 require 'nmap/command'
2 Nmap::Command.sudo do |nmap|
3 nmap.syn_scan = true
4 nmap.os_fingerprint = true
5 nmap.service_scan = true
6 nmap.output_xml = 'scan.xml'
7 nmap.verbose = true
8 nmap.ports = [20, 21, 22, 23, 25, 80, 110, 443, 512, 522, 8080, 1080]
9 nmap.targets = '10.6.6.*'
10 end
11 #Parse Nmap XML scan files:
12 require 'nmap/xml'
13 Nmap::XML.open('scan.xml') do |xml|
14 xml.each_host do |host|
15 puts "[#{host.ip}]"
16 host.each_port do |port|
17 puts " #{port.number}/#{port.protocol} #{port.state} #{port.service}"
18 end
19 end
20 end

Using the information from the chart, what scripting language interpreter will be used to run this
code?
Answer below and include screenshots.

The scripting language interpreter will be → Ruby [4]

What is the target of this Nmap scan?


Answer below and include screenshots.

The targets are the devices in the IP range of 10.6.6.0 – 10.6.6.255 10
c. Review the code sample shown. Use the syntax characteristics to determine which scripting
language is used to interpret the code.
1 $nmapExe = "Program Files (x86)Nmap
map.exe"
2 #define nmap targets
3 $target = "10.6.6.0/24", "172.17.0.0/29"
4 #run nmap scan for each target
5 foreach ($target in $target)
6 {
7 $filename = "nmap_results"
8 $nmapfile = ". emp" + $filename + $target +".xml"
9 cmd.exe /c "$nmapExe -p 20-25,80,443,3389,8080 -oX $nmapfile -A -v $target"
10 }

Using the information from the chart, what scripting language interpreter will be used to run this
code?
Answer below and include screenshots.

CSE420-Practical Lab4A: Code Automation and XSS 21


11
The scripting language interpreter will be → Powershell

What options will Nmap use for the scan and what do those options mean?
Answer below and include screenshots.

Based on the code:


12
-p 20-25,80,443,3389,8080 → only these specified ports will be scanned
-oX $nmapfile → this tells us that the output will be in XML format.
-A → will allow aggressive scanning using version detection, Os detection, etc.
-v →means that the output will provide more details about the scan. [1]

CSE420-Practical Lab4A: Code Automation and XSS 22


CSE420-Practical Lab4A: Code Automation and XSS 23
CSE420-Practical Lab4A: Code Automation and XSS 24
Part 2: Cross Site Scripting
Cross-site scripting (XSS) is a type of injection attack in which web applications accept malicious scripts
that are often appended to a URL or inserted into user-supplied text that is displayed to all visitors to a web
page. Injection attacks are among the top security risks in the OWASP Top 10, with XSS a major contributor.
We must check for XSS vulnerabilities when we are hired to test web application security.

Objectives
In this part, you will perform Reflected XSS and Stored XSS attacks against the DVWA (Damn Vulnerable
Web Application!) at low, medium, and high security levels.
• Task 2.1: Perform Reflective Cross Site Scripting Exploits
• Task 2.2: Perform Stored Cross Site Scripting Exploits

CSE420-Practical Lab4A: Code Automation and XSS 25


Background / Scenario
In this lab, you will perform penetration tests of a web application to determine if it has been securely
designed. DVWA (Damn Vulnerable Web Application!) is a PHP/MySQL web application. It is designed to
be vulnerable to common attacks to allow security professionals to test their skills and tools and students
and teachers to learn and understand web application security in a legal environment.
DVWA provides four levels of security: Low, Medium, High, and Impossible. Each security level requires
different skills to perform exploits. The security levels reflect different levels of security that developers may
code into their applications. In this lab, you will perform exploits against three of the security levels, Low,
Medium, and High, allowing you to adjust your attacks to compromise them.

Required Resources
• Kali VM customized for the Ethical Hacker course
• Internet access

Instructions

Task 2.1: Perform Reflective Cross Site Scripting Exploits


A Reflected XSS attack is one in which a malicious script is reflected off a web server to the user's browser.
The script is activated through a link that the victim clicks. This will send a request to the website that has
a vulnerability that enables execution of the malicious script.

Step 2.1.1: Log into DVWA.


a. From the Kali Linux VM, open a browser.
b. We need first to change the title of the browser tab to include the date and time, and your student
ID. Run the below commands. Use your own student ID. The title of the tab will change as shown
below.

In Kali Linux, the default web browser is usually Iceweasel, which is based on Firefox. To change
the title of a tab in Iceweasel or any other browser, you would typically need to use JavaScript. The
below simple script can do that:

You can run this script in the browser's developer console by doing the following:
1. Open your browser and navigate to the webpage whose tab title you want to change.
2. Right-click on the webpage and select "Inspect" or press `Ctrl + Shift + I` (or `Cmd + Option + I`
on Mac) to open the developer tools.
3. Go to the "Console" tab within the developer tools.
4. Paste the JavaScript code mentioned above into the console and press Enter.

CSE420-Practical Lab4A: Code Automation and XSS 26


The tab title should now be changed to "Your New Title". Remember that this change only affects
your local view of the webpage and won't change the title for other users or when you refresh the
page.

My Screenshots:

c. Navigate to the DVWA application and enter the following URL into the browser http://10.6.6.13.
d. At the login prompt, enter the credentials: admin/password.

CSE420-Practical Lab4A: Code Automation and XSS 27


CSE420-Practical Lab4A: Code Automation and XSS 28
Step 2.1.2: Perform a Reflected XSS attack at Low security level.
a. Select DVWA Security in the left menu and select Low in the Security Level dropdown. Click
Submit.

b. Select XSS (Reflected) from the left menu.


c. Type the string Reflected_Test in the What's your name? box and click Submit.

You will see the message Hello Reflected_Test appear.

d. Enter CTRL+U on the keyboard to view the source code of the page.
e. Search for the string Hello Reflected_Test by entering CTRL+F to open a search box.

The presence of the string in the page source HTML indicates that values entered in a user response
text field are inserted into the source code for the page. This indicates to an attacker that the page
may be vulnerable to reflected XSS attacks.

CSE420-Practical Lab4A: Code Automation and XSS 29


f. Close the source code window and return to the Reflected XSS Vulnerability page.
g. Enter the following payload in the What’s your name? box and click Submit.
<script>alert("You are hacked!")</script>

An alert popup box will appear with the words You are hacked!. This means the site is vulnerable
to Reflected XSS attacks and we have successfully exploited the vulnerability.

h. Select and copy the URL for the compromised page. Open a new browser tab and paste the URL
into the URL field and press <Enter>.

You should see the same web page appear displaying the You are hacked! popup box. This means
that if a user opens the URL a malicious script will execute. The alert box is used to simulate a
malicious script in this lab.

CSE420-Practical Lab4A: Code Automation and XSS 30


In an ethical hacking engagement, you would try inserting a simple test script into input fields to see
if the script executes. If so, the website is vulnerable to reflected XSS attacks. You could then
distribute the link in a phishing attack to determine the level of security awareness among your
customers’ employees.

Step 2.1.3: Perform a Reflected XSS attack at Medium security level.


You will attempt the same attack, but this time the security level of the Web site will Medium.
a. Select DVWA Security in the left menu and select Medium in the Security Level dropdown. Click
Submit.
b. Select XSS (Reflected) in the left menu.

c. Again, enter the following payload in the What's your name? box and click Submit.
<script>alert("You are hacked!")</script>

You will see a Hello response, but this time no pop up will appear. This indicates that the script did
not execute. Note that the script is displayed as literal text.

We can analyze the code in the backend of the web site to investigate the reason.

d. Click the View Source button on the bottom right of the page and review the PHP code.

Note: On a real web server, we would not have access to this backend source code, but here on
DVWS we do.

e. Note the line:


$name = str_replace ( '<script>', '', $_GET[ 'name' ] );

This source code creates a filter, with str_replace() function, that removes the <script> tag in our
payload and replaces it with a null value. This renders the payload script ineffective, so the attack
failed, and no popup window is displayed. Because this script is only filtering out <script> in lower
case, we can try and get around the filter by using a different tag in the payload. We will use
<ScRipt>.

CSE420-Practical Lab4A: Code Automation and XSS 31


f. Close the source code window and return to the Reflected XSS Vulnerability page.
g. Enter the following payload in the What's your name? box and click Submit.
<ScRipt>alert("You are hacked!")</ScRipt>

Did the popup alert appear? If so, why?


Answer below.

Yes it did appear, which indicates that the sensitive case filters “if there 14
is any” haven’t done their job.

Step 2.1.4: Perform a Reflective XSS attack at High security level.


The same attack will be attempted, but this time the security level of the website will be High.
a. Select DVWA Security in the left menu and select High in the Security Level dropdown. Click
Submit.

b. Select XSS (Reflected) in the left menu.

CSE420-Practical Lab4A: Code Automation and XSS 32


c. Enter the following payload in the What's your name? box and click Submit. (Note the use of
underscores to replace spaces.)
<ScRipt>alert("You_are_hacked!")</ScRipt>

There is a Hello message and no alert pop up box. Again, we can analyze the backend source code
to investigate.

d. Click the View Source button and review the PHP code.

Note the following line:

$name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET[ 'name' ] );

In this code, the developer used a regular expression to replace any form of the <script> tag, no
matter what case of the characters is used, with a null value.

Which character in the script was omitted from the regular expression? How do you know?
Answer below.

The character omitted from the regular expression was “e” which is in
15
“script”, you are able to tell because there is no placeholder for “e” in the
regular expression.

e. To bypass this filter, we must use another HTML tag instead of <script> to attack the site.

Close the source code window and return to the Reflected XSS Vulnerability page.

f. Enter the following payload in the What's your name? box and click Submit. (Note the use of
underscores to replace spaces.)

<img src=x onerror=alert("You_are_hacked!")>

CSE420-Practical Lab4A: Code Automation and XSS 33


The XSS popup box will appear this time. We successfully bypassed the filter and exploited the
Reflected XSS vulnerability in DVWA at High level security.

Review the text that you input into the web form. How did it work?
Answer below.

Because we didn’t use <script> which is what the backend filter was
16
looking for in order to remove it.

Task 2.2: Perform Stored Cross Site Scripting Exploits


With the stored XSS exploit, you enter a malicious script through user input and the script is stored on the
target server in a message forum, database, visitor log, or comment field. When a user visits the target, the
server exposes the user to the malicious code.

Step 2.2.1: Perform a Stored XSS attack at Low security level.


Exploiting stored XSS at low level security is easy because there are no security measures in place. You
can simply submit a <script> to achieve the exploit.
a. Select DVWA Security in the left menu and select Low in the Security Level dropdown. Click
Submit.

b. Select XSS (Stored) in the left menu.


c. Type the string XSS Test#1 in the Name* field and type Stored XSS Test in the Message * field.
click Sign Guestbook.

CSE420-Practical Lab4A: Code Automation and XSS 34


d. Enter CTRL+U on the keyboard to view the page source code. Enter CTRL+F to search for the
Test#1 and Stored XSS Test strings.

Both strings, Test#1 and Stored XSS Test, will be in the page source code indicating that the two
input fields may be vulnerable to a Stored XSS attack.

e. Close the source code window and return to the Stored XSS Vulnerability page.
f. Enter Test#1 in the Name * box and enter the following payload in the Message * field and click
Sign Guestbook.
<script>alert("You are hacked!")</script>

CSE420-Practical Lab4A: Code Automation and XSS 35


An XSS alert popup box will appear with the words You are hacked!. This means the site was
vulnerable to stored XSS attacks and we have successfully exploited the vulnerability.

g. Refresh the page. If alerted, click Resend to display the page. The XSS alert popup box will appear
again.

Because the XSS payload is stored in the guestbook, the alert popup box will appear each time the
page is refreshed.

h. Before proceeding to the next step, clear the XSS payload from the page. Click Setup / Reset DB
in the left menu then click Create / Reset Database.

Add all the Screenshots for Step 2.2.1.

I have provided the screenshots under each task. 17


CSE420-Practical Lab4A: Code Automation and XSS 36
Step 2.2.2: Perform a Stored XSS attack at Medium security level.
The same attack will be attempted, but this time the security level of the Web site will be changed to
Medium.
Exploiting reflected XSS at medium level security is not difficult. Using <script> will be rejected but changing
it to a different case such as <ScRipt> will bypass the security and achieve the exploit.
a. Select DVWA Security in the left menu and select Medium in the Security Level options dropdown.
Click Submit.

b. Select XSS (Stored) in the left menu.


c. Type the string XSS Test#1 in the Name* field and type Stored XSS Test in the Message * field.
click Sign Guestbook.

d. Enter CTRL+U on the keyboard to view the page source code. Enter CTRL+F to search for the
Test#1 and Stored XSS Test strings.

Both strings will be in the page source code indicating that the two input fields may be vulnerable to
a Stored XSS attack.

CSE420-Practical Lab4A: Code Automation and XSS 37


e. Close the source code window and return to the Vulnerability page.
f. Enter Test#1 in the Name * box and enter the following payload in the Message * box and click
Sign Guestbook.

CSE420-Practical Lab4A: Code Automation and XSS 38


<script>alert("You are hacked!")</script>

No popup box should appear. Refreshing the page should not cause the alert popup box to appear
either.

This means that there is code in the backend that is sanitizing the user input from the Message *
field to prevent scripts from being submitted. You can see the modified input in the last rectangle
message box below the input fields.

How did the input filter script modify the input?


Answer below.

It modified the input by removing raw HTML and JavaScript tags and it 18
converted the special characters to HTML, and neutralized the payload.
In this case the <script> tag was removed when the filter modified the
input.

g. Click the View Source button and review the PHP source code and investigate.

You will see two blocks of code with the word Sanitize. The first block of code, under // Sanitize
message input, contains two PHP functions for performing input sanitization. The strip_tags()
function removes all html tags from the message field before storing them in the database. The
htmlspecialchars() function converts all special characters into equivalent HTML entities so they
are not reflected back in the browser.

CSE420-Practical Lab4A: Code Automation and XSS 39


Research the PHP addslashes() function on the internet. How did it change the input?
Answer below.

It is a function used to add backlashes in front of certain or specific


19
characters in a string to help them escape, which is mainly used to
prevent an SQL injection. It changes the output as said by adding a
backlash so if there was a quotation mark, the addslashes() function
would transform it to this → /”. [5]

The second block of code, under // Sanitize name input, performs input sanitation on the Name *
field. It contains the str_replace() function which replaces any occurrence of the <script> tag with
a null value. This disables the script completely.

We can attempt to bypass the security on the Name * field by using some other payload that does
not contain <script> tags.

h. Close the source code window.


i. Before entering any payload into the Name * field, the max character length restriction of 10
characters on the field must be increased. This is a client-side setting so it is easy to change with
the following steps:
1. Right-click in the Name * field and select Inspect. This opens the Web Developer Tools
window and displays the page source code.
2. Find and double-click maxlength in the page source and change it from 10 to 100. The
maxlength property is inside the <input> tag for the text field.

3. Press Enter on the keyboard to apply the changes.


4. Close the Web Developer’s Tools Window.

CSE420-Practical Lab4A: Code Automation and XSS 40


With the maxlength restriction changed, the XSS payload can now be entered into the Name * field.

Note: Changing the maxlength parameter does not persist. If you refresh the page, for example,
the setting needs to be changed again.

j. Return to the Vulnerability page and enter the following payload in the Name * field.
<ScRipt>alert("You are hacked!")</ScRipt>

k. In the Message * field you can type any text you like and then click Sign Guestbook.

An XSS alert popup box will appear with the words You are hacked!.

Because the XSS payload is stored in the guestbook, the alert popup box will appear each time the
page is refreshed or each time other users visit the page.

The popup confirms you have successfully exploited Stored XSS vulnerability at the Medium level
of security.

l. Before proceeding to the next step, clear the XSS payload from the page. Click Setup / Reset DB
in the left menu then click Create / Reset Database.

CSE420-Practical Lab4A: Code Automation and XSS 41


20

Add all the Screenshots for Step 2.2.2.

All screenshots are added under each task.

Step 2.2.3: Perform a Stored XSS attack at High security level.


You will attempt the same attack, but this time the security level of the Web site will be set to High.
At high level the security code whitelists <scripts> and all else is rejected. However, other tags, such as
svg will work.
a. Select DVWA Security in the left menu and select High in the Security Level dropdown. Click
Submit.
b. Select XSS (Stored) in the left menu.

c. Type the string Test#1 in the Name* field and type Stored XSS Test in the Message * field. Click
Sign Guestbook.
d. Enter CTRL+U on the keyboard to view the page source code. Enter CTRL+F to search for the
Test#1 and XSS Test strings.

Both Test#1 and XSS Test should be in the page source code indicating that the two input fields
may be vulnerable to a Stored XSS attack.

CSE420-Practical Lab4A: Code Automation and XSS 42


e. Close the page source code tab and return to the Vulnerability page.
f. Enter Test#1 in the Name * box and enter the following payload in the Message * box and click
Sign Guestbook.
<ScRipt>alert("You are hacked!")</ScRipt>

No popup box will appear. Refreshing the page will not cause the alert popup box to appear either.

This means that there is code in the site backend that is sanitizing the user input from the Message
* field.

CSE420-Practical Lab4A: Code Automation and XSS 43


g. Click the View Source button and review the PHP source code and investigate.

You will see two blocks of code. As before with the Medium security, the first block of code, under //
Sanitize message input, contains two php functions for performing input sanitization. The
strip_tags() function removes all html tags from the message field before storing them in the
database. The htmlspecialchars() function converts all special characters into equivalent HTML
characters so they are not reflected back in the browser.

The second block of code, under // Sanitize name input, is performing input sanitation on the Name
* field. It contains the preg_replace() function. This function uses a regular expression to replace
any occurrence of the <script> tag, regardless of character case, with a null value.

We can attempt to bypass the security on the Name * field by using some other payload that does
not contain <script> tags.

h. Before entering any payload into the Name * field, it will be necessary to change the max character
length restriction on the field, as was done above.

With the maxlength restriction changed, the XSS payload can now be entered into the Name * field.

CSE420-Practical Lab4A: Code Automation and XSS 44


i. Return to the Vulnerability page and enter the following payload in the Name *
field. (Note the use of underscores to replace spaces.)

<svg onload=alert("You_are_hacked!")>
i. In the Message * field, you can type any text you like and then click Sign Guestbook.

An XSS alert popup box will appear with the message "You_are_hacked!".

Because the XSS payload is stored in the guestbook, the alert popup box will appear each time the
page is refreshed.

The popup confirms you have successfully exploited a Stored XSS vulnerability at High security
level.

j. Before proceeding to the next step, clear the XSS payload from the page. Click Setup / Reset DB
in the left menu then click Create / Reset Database.

CSE420-Practical Lab4A: Code Automation and XSS 45


Add all the Screenshots for Step 2.2.3.
21
All the screenshots are found under each task

Step 2.2.4: Perform a stored iframe exploit.


a. Select DVWA Security in the left menu and select Low in the Security Level dropdown. Click
Submit.

b. Select XSS (Stored) in the left menu.


c. Type the string iframe in the Name* field and type the following message in the Message * field.
click Sign Guestbook.
<iframe src="http://h4cker.org"></iframe>

The H4cker website should now be displayed under the iframe test message.

This is a powerful exploit because the threat actor could send the browser to a malicious website.

d. Before proceeding to the next step, clear the XSS payload from the page. Click Setup / Reset DB
in the left menu then click Create / Reset Database.

CSE420-Practical Lab4A: Code Automation and XSS 46


Add all the Screenshots for Step 2.2.4

22
All screenshots are found under each task.

Step 2.2.5: Perform a stored cookie exploit.

Stealing the cookies of website visitors has security implications. Cookies contain information about how
and when users visit a web site and sometimes authentication information, such as usernames and
passwords. Without proper security measures, a threat actor can capture cookies and use them to
impersonate specific users and gain access to their information and accounts.

a. Select DVWA Security in the left menu and select Low in the Security Level options dropdown.
Click Submit.

b. Select XSS (Stored) in the left menu.


c. Type the string cookie in the Name* field and type the following message in the Message * field.
click Sign Guestbook.

<script>alert(document.cookie)</script>

A popup box with the cookie will be presented. This is a cookie that PHP uses to keep of track of
running sessions.

An exploit could modify the XSS script to have the cookie sent to another destination rather than just
displaying it.

CSE420-Practical Lab4A: Code Automation and XSS 47


d. Click OK in the pop-up box.
e. Try to steal cookies at the medium and high security levels using techniques that you have learned
in this lab.

1- First is Low

2- Second is Medium

3- The third is High

CSE420-Practical Lab4A: Code Automation and XSS 48


Add all the Screenshots for Step 2.2.5.

23
All Screenshots are found under each task

References
[1] "Options Summary | NMAP Network Scanning," [Online]. Available:
https://nmap.org/book/man-briefoptions.html.
[2] "Service and version detection | NMAP network scanning," [Online]. Available:
https://nmap.org/book/man-version-detection.html.
[3] C. "GitHub - CiscoCXSecurity/Enum4Linux: Enum4Linux is a Linux alternative to
Enum.exe for enumerating data from Windows and Samba hosts," GitHub, [Online].
Available: https://github.com/CiscoCXSecurity/enum4linux.
[4] P. "GitHub - postmodern/Ruby-NMap: a Ruby interface to NMAP, the exploration tool and
Security / port Scanner. allows automating NMAP and parsing NMAP XML files.," GitHub,
[Online]. Available: https://github.com/postmodern/ruby-nmap.
[5] "PHP: Hypertext Preprocessor," [Online]. Available:
https://www.php.net/manual/en/function.addslashes.php.

CSE420-Practical Lab4A: Code Automation and XSS 49


Grading Criteria and Rules
1. This Practical Lab4A counts for 2.5%.
2. This assignment is an individual work.
3. Deadline for submission is Sunday 18th May 2024 @ 23:59.
• Any late submission will be penalized (-0.25/ day).
• Any submission via email or MS Teams will NOT be accepted.
4. Deliverables: You should upload your work via Blackboard on time before submission Deadline.
• Word file with all answers and screenshots showing that you did the practical Lab. You
are required to insert all commands and outputs (screenshots) in the document
provided, including the answers to all questions. Use references where appropriate.
5. Evaluation Rubric:
Your work will be assessed based on the following criteria:

Step Max
Part 1- Code Automation 1
Part 2- Cross-Site Scripting 1.5
Total marks: 2.5 marks

CSE420-Practical Lab4A: Code Automation and XSS 50

You might also like