from flask import Flask, render_template, request
import os
# Set the path to nmap executable
os.environ["PATH"] += os.pathsep + "C:\\Program Files (x86)\\Nmap"
import sys



# Import the scanner and CVE lookup modules
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from scanner import scan_host
from cve_lookup import search_cves

app = Flask(__name__)

# Recommended list of common ports for scanning
COMMON_PORTS = [
    21,   # FTP
    22,   # SSH
    23,   # Telnet
    25,   # SMTP
    53,   # DNS
    80,   # HTTP
    110,  # POP3
    139,  # NetBIOS
    143,  # IMAP
    443,  # HTTPS
    445,  # Microsoft-DS
    3389, # RDP
    3306, # MySQL
    8080, # HTTP-alt
    5900, # VNC
    1723, # PPTP
    8000, # Common alt HTTP
    8443, # HTTPS-alt
]

@app.route('/', methods=['GET', 'POST'])
def index():
    """
    Home page route. Displays a form to input the target and select ports to scan.
    On POST, runs the scan and matches results to CVEs.
    """
    scan_results = None
    cve_results = {}
    if request.method == 'POST':
        target = request.form.get('target')
        selected_ports = request.form.getlist('ports')
        additional_ports = request.form.get('additional_ports', '')
        # Clean and merge ports with better validation
        additional_ports_clean = []
        if additional_ports.strip():
            # Split by comma and clean each port entry
            for p in additional_ports.split(','):
                p = p.strip()
                if p:
                    # Validate port format (number or range)
                    if '-' in p:
                        # Handle port ranges like "1000-2000"
                        try:
                            start, end = p.split('-')
                            start_port = int(start.strip())
                            end_port = int(end.strip())
                            if 1 <= start_port <= 65535 and 1 <= end_port <= 65535 and start_port <= end_port:
                                additional_ports_clean.append(p)
                        except ValueError:
                            # Invalid range format, skip
                            continue
                    else:
                        # Handle single port
                        try:
                            port_num = int(p)
                            if 1 <= port_num <= 65535:
                                additional_ports_clean.append(str(port_num))
                        except ValueError:
                            # Invalid port number, skip
                            continue
        
        all_ports = selected_ports + additional_ports_clean
        ports_str = ','.join(all_ports) if all_ports else None
        # Run the scan using scanner.py
        scan_results = scan_host(target, ports=ports_str)
        # For each open port/service, look up CVEs
        if 'scan' in scan_results:
            for port_info in scan_results['scan']:
                service_name = port_info.get('name')
                version = port_info.get('version')
                # Only search if service name is available
                if service_name:
                    cve_results[port_info['port']] = []  # Don't call search_cves at all

        return render_template('index.html',
                       target=target,
                       selected_ports=selected_ports,
                       additional_ports=additional_ports,
                       all_ports=all_ports,
                       common_ports=COMMON_PORTS,
                       scan_results=scan_results,
                       cve_results=cve_results)
    # GET request: show form with default target
    return render_template('index.html',
                           target='scanme.nmap.org',
                           selected_ports=[],
                           additional_ports='',
                           all_ports=[],
                           common_ports=COMMON_PORTS,
                           scan_results=scan_results,
                           cve_results=cve_results)
@app.route('/ports')
def ports():
    return render_template('ports.html')

@app.route('/services')
def services():
    return render_template('services.html')

@app.route("/about")
def about():
    return render_template("about.html")

if __name__ == '__main__':
    app.run(debug=True)