Advertisement
AnonPastebin3

Untitled

May 21st, 2025 (edited)
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | Source Code | 0 0
  1. import time
  2. import os
  3. import sys
  4. from scapy.all import sniff, IP, UDP, TCP, Raw, conf, get_if_list
  5. import binascii
  6.  
  7. def is_admin():
  8.     try:
  9.         return os.getuid() == 0  # Unix-based systems
  10.     except AttributeError:
  11.         import ctypes
  12.         return ctypes.windll.shell32.IsUserAnAdmin() != 0  # Windows
  13.  
  14. class EnigmaIP2Monitor:
  15.     def __init__(self):
  16.         # Hardcoded parameters
  17.         self.interface = None  # Use default interface
  18.         self.host = "192.168.1.230"  # IP address of the Enigma IP2 receiver
  19.         self.port = 9999  # Receive port from settings
  20.         self.display_raw = True  # Always display raw data
  21.         self.running = False
  22.         self.packet_count = 0
  23.        
  24.     def packet_callback(self, packet):
  25.         """Process each captured packet"""
  26.         self.packet_count += 1
  27.         print(f"Packet #{self.packet_count} received")
  28.        
  29.         # Check if it's an IP packet
  30.         if IP in packet:
  31.             src_ip = packet[IP].src
  32.             dst_ip = packet[IP].dst
  33.            
  34.             # Filter by Enigma IP2 receiver address
  35.             if not (src_ip == self.host or dst_ip == self.host):
  36.                 print(f"Skipping packet with IPs: {src_ip} -> {dst_ip} (not matching {self.host})")
  37.                 return
  38.            
  39.             # Extract transport layer details
  40.             transport_protocol = None
  41.             src_port = None
  42.             dst_port = None
  43.             payload = None
  44.            
  45.             if TCP in packet:
  46.                 transport_protocol = "TCP"
  47.                 src_port = packet[TCP].sport
  48.                 dst_port = packet[TCP].dport
  49.                 if Raw in packet:
  50.                     payload = packet[Raw].load
  51.             elif UDP in packet:
  52.                 transport_protocol = "UDP"
  53.                 src_port = packet[UDP].sport
  54.                 dst_port = packet[UDP].dport
  55.                 if Raw in packet:
  56.                     payload = packet[Raw].load
  57.            
  58.             # Filter by port
  59.             if not (src_port == self.port or dst_port == self.port):
  60.                 print(f"Skipping packet with ports: {src_port} -> {dst_port} (not matching {self.port})")
  61.                 return
  62.            
  63.             # Display packet information
  64.             print(f"\n{'='*60}")
  65.             print(f"Time: {time.strftime('%Y-%m-%d %H:%M:%S')}")
  66.             print(f"Protocol: {transport_protocol}")
  67.             print(f"Source: {src_ip}:{src_port}")
  68.             print(f"Destination: {dst_ip}:{dst_port}")
  69.            
  70.             if payload:
  71.                 print(f"Payload Length: {len(payload)} bytes")
  72.                 print("Raw Payload (hex):")
  73.                 print(binascii.hexlify(payload).decode())
  74.                 print("Raw Payload (ascii):")
  75.                 try:
  76.                     print(payload.decode('ascii', errors='replace'))
  77.                 except:
  78.                     print("Unable to decode as ASCII")
  79.             print(f"{'='*60}")
  80.    
  81.     def start_capture(self, less_restrictive=False):
  82.         """Start capturing packets"""
  83.         try:
  84.             self.running = True
  85.             print(f"Starting packet capture for Enigma IP2")
  86.             print(f"Monitoring IP: {self.host} on port: {self.port}")
  87.            
  88.             if self.interface:
  89.                 print(f"Using interface: {self.interface}")
  90.             else:
  91.                 print("Using default interface")
  92.                
  93.             print("Press Ctrl+C to stop capturing")
  94.            
  95.             # Define the BPF filter
  96.             bpf_filter = None
  97.             if not less_restrictive:
  98.                 bpf_filter = f"host {self.host} and port {self.port}"
  99.                 print(f"Using filter: {bpf_filter}")
  100.             else:
  101.                 bpf_filter = f"host {self.host}"
  102.                 print(f"Using less restrictive filter: {bpf_filter}")
  103.            
  104.             # Start sniffing
  105.             sniff(
  106.                 iface=self.interface,
  107.                 filter=bpf_filter,
  108.                 prn=self.packet_callback,
  109.                 store=0
  110.             )
  111.         except KeyboardInterrupt:
  112.             print("\nPacket capture stopped by user")
  113.         except Exception as e:
  114.             print(f"Error during packet capture: {e}")
  115.         finally:
  116.             self.running = False
  117.  
  118. def list_interfaces():
  119.     """Display all available network interfaces"""
  120.     print("\nAvailable Network Interfaces:")
  121.     for i, iface in enumerate(get_if_list()):
  122.         print(f"{i+1}. {iface}")
  123.     print()
  124.  
  125. if __name__ == "__main__":
  126.     # Check for admin privileges
  127.     if not is_admin():
  128.         print("WARNING: This script may need administrator privileges to capture packets.")
  129.         print("Try running as administrator/with sudo if no packets are captured.")
  130.    
  131.     # Display available interfaces
  132.     list_interfaces()
  133.    
  134.     # Create monitor with hardcoded settings
  135.     monitor = EnigmaIP2Monitor()
  136.    
  137.     # Allow user to select interface
  138.     use_specific_interface = input("Do you want to specify a network interface? (y/n): ").lower() == 'y'
  139.     if use_specific_interface:
  140.         interface_idx = int(input("Enter the number of the interface to use: ")) - 1
  141.         monitor.interface = get_if_list()[interface_idx]
  142.    
  143.     # First try with normal filter
  144.     print("\nStarting capture with standard filter...")
  145.     monitor.start_capture(less_restrictive=False)
  146.    
  147.     # If no packets were captured, try with less restrictive filter
  148.     if monitor.packet_count == 0:
  149.         print("\nNo packets captured. Trying with less restrictive filter (host only)...")
  150.         monitor.start_capture(less_restrictive=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement