#!/usr/bin/env python3
"""
Interactive Colorful Shell for SMB Exploitation Tool
Provides a rich, colorful terminal interface for security testing
"""

import sys
import os
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.prompt import Prompt, Confirm
from rich.syntax import Syntax
from rich import box
from rich.text import Text
from rich.markdown import Markdown
from rich.progress import Progress, SpinnerColumn, TextColumn
import time

console = Console()

class InteractiveSMBShell:
    """Interactive shell with colorful UI for SMB exploitation tool"""

    def __init__(self):
        self.targets = []
        self.ports = "139,445"
        self.duration = 1200
        self.evasion_level = 3
        self.output_file = "exploitation_results.json"
        self.reverse_shell_port = 4444
        self.reverse_shell_ip = None
        self.no_exploit = False
        self.http_tunnel = False

    def display_banner(self):
        """Display colorful banner"""
        banner = """
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║   ███████╗███╗   ███╗██████╗     ███████╗██╗  ██╗██████╗     ║
║   ██╔════╝████╗ ████║██╔══██╗    ██╔════╝╚██╗██╔╝██╔══██╗    ║
║   ███████╗██╔████╔██║██████╔╝    █████╗   ╚███╔╝ ██████╔╝    ║
║   ╚════██║██║╚██╔╝██║██╔══██╗    ██╔══╝   ██╔██╗ ██╔═══╝     ║
║   ███████║██║ ╚═╝ ██║██████╔╝    ███████╗██╔╝ ██╗██║         ║
║   ╚══════╝╚═╝     ╚═╝╚═════╝     ╚══════╝╚═╝  ╚═╝╚═╝         ║
║                                                               ║
║         Advanced SMB Exploitation Framework                   ║
║         For Authorized Security Testing Only                  ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝
        """
        console.print(banner, style="bold cyan")
        console.print()

    def display_menu(self):
        """Display main menu"""
        menu = Table(show_header=False, box=box.ROUNDED, border_style="cyan")
        menu.add_column("Option", style="bold yellow", width=20)
        menu.add_column("Description", style="white")

        menu.add_row("1", "Configure Target(s)")
        menu.add_row("2", "Configure Ports")
        menu.add_row("3", "Set Assessment Duration")
        menu.add_row("4", "Set Evasion Level")
        menu.add_row("5", "Configure Reverse Shell")
        menu.add_row("6", "Enable/Disable Exploitation")
        menu.add_row("7", "Enable HTTP Tunneling")
        menu.add_row("8", "View Current Configuration")
        menu.add_row("9", "Start Assessment")
        menu.add_row("10", "Run Quick Scan")
        menu.add_row("0", "Exit")

        console.print(Panel(menu, title="[bold white]Main Menu[/bold white]", border_style="cyan"))

    def configure_targets(self):
        """Configure target hosts"""
        console.print("\n[bold cyan]Configure Targets[/bold cyan]", style="bold")
        console.print("You can enter:")
        console.print("  • Single IP: 192.168.1.100")
        console.print("  • Multiple IPs: 192.168.1.100,192.168.1.101")
        console.print("  • File path: /path/to/targets.txt")
        console.print()

        target_input = Prompt.ask("[yellow]Enter target(s)[/yellow]")

        if os.path.isfile(target_input):
            with open(target_input, 'r') as f:
                self.targets = [line.strip() for line in f if line.strip() and not line.startswith('#')]
            console.print(f"[green]✓[/green] Loaded {len(self.targets)} targets from file")
        else:
            self.targets = [t.strip() for t in target_input.split(',') if t.strip()]
            console.print(f"[green]✓[/green] Added {len(self.targets)} target(s)")

    def configure_ports(self):
        """Configure SMB ports"""
        console.print("\n[bold cyan]Configure Ports[/bold cyan]")
        console.print(f"Current ports: [yellow]{self.ports}[/yellow]")

        new_ports = Prompt.ask(
            "[yellow]Enter port(s) (comma-separated)[/yellow]",
            default=self.ports
        )
        self.ports = new_ports
        console.print("[green]✓[/green] Ports updated")

    def configure_duration(self):
        """Configure assessment duration"""
        console.print("\n[bold cyan]Configure Assessment Duration[/bold cyan]")
        console.print(f"Current duration: [yellow]{self.duration}[/yellow] seconds")

        duration = Prompt.ask(
            "[yellow]Enter duration (seconds)[/yellow]",
            default=str(self.duration)
        )
        self.duration = int(duration)
        console.print(f"[green]✓[/green] Duration set to {self.duration} seconds")

    def configure_evasion(self):
        """Configure evasion level"""
        console.print("\n[bold cyan]Configure Evasion Level[/bold cyan]")

        evasion_table = Table(box=box.SIMPLE)
        evasion_table.add_column("Level", style="yellow")
        evasion_table.add_column("Description", style="white")

        evasion_table.add_row("0", "No evasion techniques")
        evasion_table.add_row("1", "Basic evasion (fragmentation, delays)")
        evasion_table.add_row("2", "Moderate evasion (+ junk data, protocol switching)")
        evasion_table.add_row("3", "Advanced evasion (+ SSL/HTTP tunneling, traffic morphing)")

        console.print(evasion_table)
        console.print(f"\nCurrent level: [yellow]{self.evasion_level}[/yellow]")

        level = Prompt.ask(
            "[yellow]Select evasion level (0-3)[/yellow]",
            default=str(self.evasion_level),
            choices=["0", "1", "2", "3"]
        )
        self.evasion_level = int(level)
        console.print(f"[green]✓[/green] Evasion level set to {self.evasion_level}")

    def configure_reverse_shell(self):
        """Configure reverse shell settings"""
        console.print("\n[bold cyan]Configure Reverse Shell[/bold cyan]")

        console.print(f"Current port: [yellow]{self.reverse_shell_port}[/yellow]")
        port = Prompt.ask(
            "[yellow]Enter reverse shell port[/yellow]",
            default=str(self.reverse_shell_port)
        )
        self.reverse_shell_port = int(port)

        if Confirm.ask("[yellow]Specify custom IP for reverse shell?[/yellow]", default=False):
            ip = Prompt.ask("[yellow]Enter IP address[/yellow]")
            self.reverse_shell_ip = ip

        console.print("[green]✓[/green] Reverse shell configured")

    def toggle_exploitation(self):
        """Toggle exploitation mode"""
        console.print("\n[bold cyan]Exploitation Mode[/bold cyan]")
        console.print(f"Current mode: [yellow]{'Disabled' if self.no_exploit else 'Enabled'}[/yellow]")

        self.no_exploit = not Confirm.ask(
            "[yellow]Enable exploitation attempts?[/yellow]",
            default=not self.no_exploit
        )

        status = "disabled" if self.no_exploit else "enabled"
        console.print(f"[green]✓[/green] Exploitation {status}")

    def toggle_http_tunnel(self):
        """Toggle HTTP tunneling"""
        console.print("\n[bold cyan]HTTP Tunneling[/bold cyan]")
        console.print(f"Current status: [yellow]{'Enabled' if self.http_tunnel else 'Disabled'}[/yellow]")

        self.http_tunnel = Confirm.ask(
            "[yellow]Enable HTTP tunneling?[/yellow]",
            default=self.http_tunnel
        )

        status = "enabled" if self.http_tunnel else "disabled"
        console.print(f"[green]✓[/green] HTTP tunneling {status}")

    def view_configuration(self):
        """Display current configuration"""
        console.print()

        config_table = Table(title="Current Configuration", box=box.ROUNDED, border_style="cyan")
        config_table.add_column("Setting", style="bold yellow")
        config_table.add_column("Value", style="white")

        config_table.add_row("Targets", str(len(self.targets)) + " target(s)" if self.targets else "Not configured")
        if self.targets:
            for target in self.targets[:5]:
                config_table.add_row("", f"  → {target}")
            if len(self.targets) > 5:
                config_table.add_row("", f"  ... and {len(self.targets) - 5} more")

        config_table.add_row("Ports", self.ports)
        config_table.add_row("Duration", f"{self.duration} seconds")
        config_table.add_row("Evasion Level", str(self.evasion_level))
        config_table.add_row("Exploitation", "Disabled" if self.no_exploit else "Enabled")
        config_table.add_row("HTTP Tunneling", "Enabled" if self.http_tunnel else "Disabled")
        config_table.add_row("Reverse Shell Port", str(self.reverse_shell_port))
        config_table.add_row("Reverse Shell IP", self.reverse_shell_ip or "Auto-detect")
        config_table.add_row("Output File", self.output_file)

        console.print(config_table)
        console.print()

    def start_assessment(self):
        """Start the assessment"""
        if not self.targets:
            console.print("[bold red]✗ No targets configured![/bold red]")
            return

        console.print("\n[bold cyan]Starting Assessment[/bold cyan]")
        self.view_configuration()

        if not Confirm.ask("[bold yellow]Start assessment with these settings?[/bold yellow]", default=True):
            return

        # Build command
        cmd_args = [
            sys.executable,
            "-m", "smb_exploitation_tool_pkg.cli",
            "--target", ",".join(self.targets),
            "-p", self.ports,
            "-d", str(self.duration),
            "-e", str(self.evasion_level),
            "-o", self.output_file,
            "--reverse-shell-port", str(self.reverse_shell_port)
        ]

        if self.reverse_shell_ip:
            cmd_args.extend(["--reverse-shell-ip", self.reverse_shell_ip])

        if self.no_exploit:
            cmd_args.append("--no-exploit")

        if self.http_tunnel:
            cmd_args.append("--http-tunnel")

        console.print("\n[bold green]Launching assessment...[/bold green]")
        console.print(f"[dim]Command: {' '.join(cmd_args)}[/dim]\n")

        import subprocess
        try:
            subprocess.run(cmd_args)
        except KeyboardInterrupt:
            console.print("\n[yellow]Assessment interrupted by user[/yellow]")
        except Exception as e:
            console.print(f"[red]Error: {str(e)}[/red]")

    def quick_scan(self):
        """Run a quick scan"""
        if not self.targets:
            console.print("[bold red]✗ No targets configured![/bold red]")
            return

        console.print("\n[bold cyan]Quick Scan Mode[/bold cyan]")
        console.print("Duration: 60 seconds")
        console.print("Evasion: Level 1")
        console.print("Exploitation: Disabled\n")

        if not Confirm.ask("[yellow]Start quick scan?[/yellow]", default=True):
            return

        cmd_args = [
            sys.executable,
            "-m", "smb_exploitation_tool_pkg.cli",
            "--target", ",".join(self.targets),
            "-p", self.ports,
            "-d", "60",
            "-e", "1",
            "--no-exploit",
            "-o", "quick_scan_results.json"
        ]

        console.print("[bold green]Starting quick scan...[/bold green]\n")

        import subprocess
        try:
            subprocess.run(cmd_args)
        except KeyboardInterrupt:
            console.print("\n[yellow]Scan interrupted by user[/yellow]")
        except Exception as e:
            console.print(f"[red]Error: {str(e)}[/red]")

    def run(self):
        """Main loop"""
        self.display_banner()

        console.print(Panel(
            "[bold yellow]⚠ WARNING ⚠[/bold yellow]\n\n"
            "This tool is for [bold]AUTHORIZED SECURITY TESTING ONLY[/bold].\n"
            "Unauthorized access to computer systems is illegal.\n"
            "Ensure you have proper authorization before proceeding.",
            border_style="red",
            box=box.DOUBLE
        ))

        if not Confirm.ask("\n[bold yellow]I confirm I have authorization to perform security testing[/bold yellow]", default=False):
            console.print("[red]Authorization not confirmed. Exiting.[/red]")
            return

        while True:
            console.print()
            self.display_menu()

            choice = Prompt.ask(
                "\n[bold yellow]Select an option[/bold yellow]",
                choices=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
            )

            if choice == "0":
                console.print("\n[bold cyan]Goodbye![/bold cyan]")
                break
            elif choice == "1":
                self.configure_targets()
            elif choice == "2":
                self.configure_ports()
            elif choice == "3":
                self.configure_duration()
            elif choice == "4":
                self.configure_evasion()
            elif choice == "5":
                self.configure_reverse_shell()
            elif choice == "6":
                self.toggle_exploitation()
            elif choice == "7":
                self.toggle_http_tunnel()
            elif choice == "8":
                self.view_configuration()
            elif choice == "9":
                self.start_assessment()
            elif choice == "10":
                self.quick_scan()

            time.sleep(0.5)


def main():
    """Entry point for interactive shell"""
    try:
        shell = InteractiveSMBShell()
        shell.run()
    except KeyboardInterrupt:
        console.print("\n\n[yellow]Interrupted by user. Exiting...[/yellow]")
    except Exception as e:
        console.print(f"\n[bold red]Error: {str(e)}[/bold red]")
        import traceback
        console.print(traceback.format_exc())


if __name__ == "__main__":
    main()
