Advertisement
xosski

Bluetooth hunter/sniffer

Dec 13th, 2024
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.92 KB | None | 0 0
  1. import bluetooth
  2. import time
  3. import logging
  4. import sys
  5. import signal
  6. import socket
  7. import os
  8. import platform
  9. import threading
  10. import configparser
  11. import tkinter as tk
  12. from tkinter import messagebox
  13. from datetime import datetime
  14. import asyncio
  15.  
  16. # Configure logging
  17. logging.basicConfig(
  18. filename="bluetooth_tool.log",
  19. level=logging.DEBUG, # Default to DEBUG for more verbosity
  20. format='%(asctime)s - %(levelname)s - %(message)s'
  21. )
  22. logger = logging.getLogger()
  23.  
  24. # Graceful exit handler
  25. def signal_handler(sig, frame):
  26. print("\nGracefully exiting the Bluetooth tool.")
  27. logger.info("Tool was terminated by user.")
  28. sys.exit(0)
  29.  
  30. # Attach the signal handler for graceful exit
  31. signal.signal(signal.SIGINT, signal_handler)
  32.  
  33. # Configuration handler
  34. class Config:
  35. def __init__(self):
  36. self.config = configparser.ConfigParser()
  37. self.config.read("settings.ini")
  38.  
  39. def get(self, section, key):
  40. try:
  41. return self.config.get(section, key)
  42. except KeyError as e:
  43. logger.error(f"KeyError: {e} - Missing in config file.")
  44. return None
  45.  
  46. def set(self, section, key, value):
  47. self.config.set(section, key, value)
  48. with open("settings.ini", "w") as configfile:
  49. self.config.write(configfile)
  50.  
  51. # Scan Bluetooth devices
  52. async def scan_devices():
  53. """Scan for nearby Bluetooth devices and return the list of devices with IPs if available."""
  54. logger.info("Scanning for Bluetooth devices...")
  55. nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True, lookup_uuids=True, flush_cache=True)
  56.  
  57. devices_info = []
  58.  
  59. if not nearby_devices:
  60. logger.warning("No Bluetooth devices found.")
  61. return devices_info
  62. else:
  63. logger.info(f"Found {len(nearby_devices)} Bluetooth devices.")
  64. for addr, name in nearby_devices:
  65. try:
  66. device_ip = await get_device_ip(addr)
  67. device_info = {"address": addr, "name": name, "ip": device_ip}
  68. devices_info.append(device_info)
  69. except Exception as e:
  70. logger.warning(f"Could not retrieve IP for {addr}: {e}")
  71.  
  72. return devices_info
  73.  
  74. async def get_device_ip(device_address):
  75. """Try to get the IP address of the Bluetooth device (based on network services)."""
  76. try:
  77. host_ip = socket.gethostbyname(device_address)
  78. return host_ip
  79. except socket.gaierror:
  80. return "Not Available"
  81.  
  82. # Connect to a Bluetooth device (simulated)
  83. async def connect_to_device(device_address):
  84. """Attempt to connect to a Bluetooth device using its address."""
  85. try:
  86. sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  87. sock.connect((device_address, 1)) # RFCOMM channel 1
  88. logger.info(f"Connected to device: {device_address}")
  89. return sock
  90. except bluetooth.BluetoothError as e:
  91. logger.error(f"Failed to connect to {device_address}: {e}")
  92. return None
  93.  
  94. async def send_data(sock, message):
  95. """Send data to the connected Bluetooth device."""
  96. try:
  97. sock.send(message)
  98. logger.info(f"Sent message: {message}")
  99. except bluetooth.BluetoothError as e:
  100. logger.error(f"Failed to send data: {e}")
  101.  
  102. async def disconnect_device(sock):
  103. """Disconnect from the Bluetooth device."""
  104. try:
  105. sock.close()
  106. logger.info("Disconnected from the device.")
  107. except bluetooth.BluetoothError as e:
  108. logger.error(f"Failed to disconnect: {e}")
  109.  
  110. # Block the device IP for a certain duration using the system firewall
  111. async def block_ip(ip_address, duration=30):
  112. """Simulate blocking a device by IP using system firewall tools."""
  113. system = platform.system().lower()
  114. try:
  115. if system == 'linux':
  116. os.system(f"sudo iptables -A INPUT -s {ip_address} -j DROP")
  117. await asyncio.sleep(duration)
  118. os.system(f"sudo iptables -D INPUT -s {ip_address} -j DROP")
  119. elif system == 'darwin': # macOS
  120. os.system(f"sudo pfctl -t blocklist -T add {ip_address}")
  121. await asyncio.sleep(duration)
  122. os.system(f"sudo pfctl -t blocklist -T delete {ip_address}")
  123. elif system == 'windows':
  124. os.system(f"netsh advfirewall firewall add rule name=\"Block {ip_address}\" dir=in action=block remoteip={ip_address}")
  125. await asyncio.sleep(duration)
  126. os.system(f"netsh advfirewall firewall delete rule name=\"Block {ip_address}\"")
  127. else:
  128. logger.error(f"Unsupported OS: {system}")
  129. except Exception as e:
  130. logger.error(f"Error blocking IP {ip_address}: {e}")
  131.  
  132. # Function to perform persistent monitoring and blocking
  133. async def persistent_monitoring(devices_info, block_duration=30, gui_update_callback=None):
  134. """Monitor and interact with Bluetooth devices persistently."""
  135. while True:
  136. devices = await scan_devices()
  137.  
  138. if devices:
  139. for device in devices:
  140. ip = device['ip']
  141. if ip != "Not Available":
  142. await block_ip(ip, block_duration)
  143. if gui_update_callback:
  144. gui_update_callback(f"Blocked IP: {ip}")
  145.  
  146. for device in devices:
  147. device_address = device['address']
  148. sock = await connect_to_device(device_address)
  149.  
  150. if sock:
  151. await send_data(sock, "Hello, this is an ethical penetration test message.")
  152. await asyncio.sleep(10) # Keep the connection alive for 10 seconds
  153. await disconnect_device(sock)
  154. await asyncio.sleep(2)
  155.  
  156. await asyncio.sleep(30)
  157.  
  158. # Function to handle the GUI
  159. class BluetoothToolGUI:
  160. def __init__(self, root):
  161. self.root = root
  162. self.root.title("Bluetooth Persistence and Blocking Tool")
  163. self.root.geometry("500x300")
  164.  
  165. self.label = tk.Label(self.root, text="Bluetooth Tool", font=("Helvetica", 16))
  166. self.label.pack(pady=20)
  167.  
  168. self.start_button = tk.Button(self.root, text="Start Monitoring", command=self.start_monitoring)
  169. self.start_button.pack(pady=10)
  170.  
  171. self.status_label = tk.Label(self.root, text="Status: Idle", font=("Helvetica", 12))
  172. self.status_label.pack(pady=10)
  173.  
  174. self.log_text = tk.Text(self.root, height=8, width=50)
  175. self.log_text.pack(pady=10)
  176. self.log_text.config(state=tk.DISABLED)
  177.  
  178. def update_log(self, message):
  179. """Update the log area in the GUI."""
  180. self.log_text.config(state=tk.NORMAL)
  181. self.log_text.insert(tk.END, message + '\n')
  182. self.log_text.config(state=tk.DISABLED)
  183. self.log_text.yview(tk.END)
  184.  
  185. def start_monitoring(self):
  186. """Start monitoring in a separate thread to avoid blocking the GUI."""
  187. self.status_label.config(text="Status: Monitoring...")
  188. threading.Thread(target=self.monitor_devices, daemon=True).start()
  189.  
  190. def monitor_devices(self):
  191. """Wrapper for persistent monitoring in a separate thread."""
  192. config = Config()
  193. block_duration = int(config.get("settings", "block_duration") or 30)
  194. try:
  195. devices_info = asyncio.run(scan_devices())
  196. if not devices_info:
  197. self.update_log("No devices found.")
  198. return
  199.  
  200. self.update_log("Starting monitoring and blocking devices...")
  201. asyncio.run(persistent_monitoring(devices_info, block_duration, self.update_log))
  202.  
  203. except Exception as e:
  204. logger.error(f"Unexpected error: {e}")
  205. self.update_log(f"Error: {e}")
  206.  
  207. # Main function to set up the GUI
  208. def main():
  209. root = tk.Tk()
  210. gui = BluetoothToolGUI(root)
  211. root.mainloop()
  212.  
  213. if __name__ == "__main__":
  214. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement