Man-in-the-Middle Attacks: JavaScript Injection

Understanding the capabilities and techniques of ethical penetration testing

Introduction to Man-in-the-Middle Capabilities

As a man-in-the-middle (MITM) attacker, you gain significant visibility and control over network traffic between a target and the internet. This position allows you to:

Injecting JavaScript Code

One of the most powerful MITM capabilities is the ability to inject JavaScript code into web pages as they load. JavaScript allows attackers to:

Simple JavaScript Injection Example

Below is a simple JavaScript code that will display an alert message when injected into a web page:

alert('javascript test');

This code (saved as alert.js) will display a popup with the message "JavaScript test" whenever it's injected into a page loaded by the target.

Configuring Bettercap for JavaScript Injection

HSTS Hijack Plugin Configuration

To inject JavaScript code using Bettercap's HSTS hijack plugin, follow these steps:

Step 1: Create JavaScript File

Create a file named alert.js with the following content:

alert('javascript test');

Step 2: Configure HSTS Hijack Plugin

Modify the hstshijack.cap file to include your JavaScript file:

set hstshijack.payloads *:/root/alert.js

The asterisk (*) means inject into all domains. You can specify particular domains instead.

Step 3: Run Bettercap with the Plugin

Execute Bettercap with the following command:

sudo bettercap -iface eth0 -caplet spoof.cap

Then run the HSTS hijack plugin:

hstshijack/hstshijack

Attack Scenarios and Examples

Website Type Protection Attack Method Success Rate
HTTP Websites None Direct code injection High (100%)
HTTPS Websites TLS/SSL Encryption HTTPS stripping via ARP spoofing High (if no HSTS)
HSTS Websites HTTP Strict Transport Security Domain spoofing (e.g., .com → .corn) Medium (depends on user behavior)
Note: If a user manually types a domain with HSTS enabled (e.g., facebook.com), the browser will force HTTPS, making the injection fail. This attack works best when users click links or search for websites rather than typing domains directly.

Key Takeaways