Automação de scan de vulnerabilidades

Publicado por Dionata Suzin (última atualização em 11/10/2024)

[ Hits: 1.293 ]

Download VM.py




Script para automação de scan de vulnerabilidades

  



Esconder código-fonte

import os
import subprocess
import tempfile
import csv
import re
import openpyxl
from openpyxl.styles import Font
from datetime import datetime
from concurrent.futures import ProcessPoolExecutor, as_completed

# Função para executar um comando de shell e capturar a saída
def run_command(command):
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return result.stdout, result.returncode

# Função para escanear um host
def scan_host(ip):
    with tempfile.NamedTemporaryFile(delete=False) as nmap_output:
        nmap_cmd = f"nmap -sV -O -R --script nmap-vulners/ --open -Pn -oN {nmap_output.name} {ip}"
        output, return_code = run_command(nmap_cmd)
        
        result = {
            "ip": ip,
            "nmap_output": nmap_output.name,
            "return_code": return_code
        }
        return result

# Excluir diretório nmap-vulners se existir
if os.path.exists('nmap-vulners'):
    os.system('rm -rf nmap-vulners')

# Baixar nmap-vulners atualizado
run_command('git clone https://github.com/vulnersCom/nmap-vulners.git')

# Atualizar banco de dados de scripts do Nmap
run_command('nmap --script-updatedb')

# Faixa de IPs
start_ip = 1
end_ip = 254
base_ip = "192.168.0."

# Diretório para salvar os relatórios
report_dir = "/home/kali/Desktop/VM"
if not os.path.exists(report_dir):
    print(f"Diretório de relatório {report_dir} não existe. Criando...")
    os.makedirs(report_dir)

# Adiciona timestamp ao nome do arquivo HTML para torná-lo único
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
summary_report_html = os.path.join(report_dir, f"summary_report_{timestamp}.html")
csv_report = os.path.join(report_dir, f"summary_report_{timestamp}.csv")
excel_report = os.path.join(report_dir, "scan_history.xlsx")

# Inicializa o conteúdo do relatório HTML
html_content = """
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relatório de Scan</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 1200px;
            margin: 30px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
            font-size: 24px;
            margin-bottom: 40px;
        }
        h2 {
            color: #4CAF50;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
        }
        td {
            background-color: #f9f9f9;
        }
        .host-summary {
            font-size: 16px;
            margin-top: 10px;
            line-height: 1.6;
        }
        .exploit-warning {
            color: #e74c3c;
            font-weight: bold;
        }
        hr {
            border: none;
            height: 1px;
            background-color: #ddd;
            margin: 30px 0;
        }
        .footer {
            text-align: center;
            margin-top: 50px;
            color: #777;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Relatório de Scan de Rede</h1>
"""

# Inicializa o conteúdo do CSV
csv_data = [["Host", "Porta", "Serviço", "Versão", "Vulnerabilidade", "Criticidade", "Exploit Disponível", "Score Total"]]

# Inicializa ou abre o arquivo Excel
if not os.path.exists(excel_report):
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "Histórico de Scans"
    # Cabeçalhos
    sheet.append(["Host", "Data/Hora", "Portas Abertas", "Vulnerabilidades", "Exploits", "Score Total"])
else:
    workbook = openpyxl.load_workbook(excel_report)
    sheet = workbook.active

# Função para processar os resultados do scan de cada IP
def process_scan_result(result):
    current_ip = result["ip"]
    nmap_output = result["nmap_output"]
    return_code = result["return_code"]
    
    if return_code == 0:
        print(f"Scan concluído para o IP: {current_ip}.")
        
        html_content = f"<h2>Host: {current_ip}</h2>"
        html_content += "<table><tr><th>Porta</th><th>Serviço</th><th>Versão</th><th>Vulnerabilidade</th><th>Score</th><th>Link</th></tr>"
        
        host_score = 0
        total_ports = 0
        total_vulnerabilities = 0
        exploits_found = False
        total_exploits = 0  # Inicializa o contador de exploits
        os_version = "N/A"
        hostname = "N/A"
        
        with open(nmap_output, "r") as output:
            for line in output:
                if "open" in line:
                    parts = line.split()
                    if len(parts) >= 3:
                        port = parts[0]
                        service = parts[2]
                        version = ' '.join(parts[3:]) if len(parts) > 3 else 'N/A'
                        html_content += f"<tr><td>{port}</td><td>{service}</td><td>{version}</td><td></td><td></td><td></td></tr>"
                        csv_data.append([current_ip, port, service, version, "", "", "", ""])
                        total_ports += 1
                        host_score += 1
                
                if "OS details" in line:
                    os_version = line.split("OS details: ")[1].strip()

                if "Running: " in line:
                    os_version = line.split("Running: ")[1].strip()

                if "Computer name" in line:
                    hostname = line.split("Computer name: ")[1].strip()

                # Contar todas as linhas de vulnerabilidades
                if "VULNERABLE:" in line or "CVE" in line:
                    vuln_match = re.search(r'(CVE-\d{4}-\d{4,7})\s+(\d+\.\d+)\s+(https?://\S+)', line)
                    if vuln_match:
                        cve_id = vuln_match.group(1).replace("-", "_")  # Substitui '-' por '_'
                        score = vuln_match.group(2)
                        link = vuln_match.group(3)
                        
                        # Adiciona a vulnerabilidade na tabela HTML
                        html_content += f"<tr><td></td><td></td><td></td><td>{cve_id}</td><td>{score}</td><td><a href='{link}'>Link</a></td></tr>"
                        csv_data.append([current_ip, "", "", "", cve_id, score, "", ""])
                        total_vulnerabilities += 1  # Incrementa a contagem de vulnerabilidades
                        host_score += 1  # Adiciona 1 ponto ao score do host

                # Captura exploits disponíveis
                if "EXPLOIT" in line.upper():
                    exploit_match = re.search(r'(\S+)\s+(\d+\.\d+)\s+(https?://\S+)\s+\*EXPLOIT\*', line)
                    if exploit_match:
                        exploit_id = exploit_match.group(1)
                        exploit_score = float(exploit_match.group(2))
                        exploit_link = exploit_match.group(3)
                        html_content += f"<tr><td></td><td></td><td></td><td>{exploit_id}</td><td>{int(exploit_score)}</td><td><a href='{exploit_link}'>Link</a></td></tr>"
                        csv_data.append([current_ip, "", "", "", exploit_id, exploit_score, "Sim", ""])
                        total_exploits += 1  # Incrementa o contador de exploits
                        host_score += 10  # Adiciona 10 pontos ao score do host
                        exploits_found = True

        html_content += "</table>"
        
        if total_vulnerabilities == 0 and not exploits_found:
            # Caso não haja vulnerabilidades ou exploits, o host não será exibido
            print(f"Host {current_ip} não tem vulnerabilidades nem exploits, não será exibido no relatório.")
            return None
        
        # Adiciona o resumo do host no relatório HTML
        html_content += f"""
        <div class="host-summary">
            <strong>IP:</strong> {current_ip}<br>
            <strong>Sistema Operacional:</strong> {os_version}<br>
            <strong>Hostname:</strong> {hostname}<br>
            <strong>Total de portas abertas:</strong> {total_ports}<br>
            <strong>Total de vulnerabilidades:</strong> {total_vulnerabilities}<br>
            <strong>Exploits encontrados:</strong> {total_exploits if total_exploits > 0 else 'Nenhum'}<br>
            <strong>Score do host:</strong> {int(host_score)}
        </div>
        <hr>
        """
        
        # Adiciona a linha no Excel
        sheet.append([current_ip, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), total_ports, total_vulnerabilities, total_exploits, int(host_score)])

        return html_content
    else:
        print(f"Falha ao escanear o IP {current_ip}. Código de retorno: {return_code}")
        return None

# Função principal para escanear a faixa de IPs
def scan_network():
    ips_to_scan = [f"{base_ip}{i}" for i in range(start_ip, end_ip + 1)]
    all_hosts_data = []

    with ProcessPoolExecutor(max_workers=10) as executor:
        future_to_ip = {executor.submit(scan_host, ip): ip for ip in ips_to_scan}

        for future in as_completed(future_to_ip):
            try:
                result = future.result()
                if result:
                    host_html = process_scan_result(result)
                    if host_html:
                        all_hosts_data.append(host_html)
            except Exception as e:
                print(f"Erro ao processar resultado de um host: {e}")

    return all_hosts_data

# Executa o scan e processa os resultados
all_hosts_html = scan_network()

# Salva o relatório HTML
with open(summary_report_html, "w") as f:
    f.write(html_content)
    for host_html in all_hosts_html:
        f.write(host_html)
    f.write("""
    <div class="footer">
        Relatório gerado em: """ + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + """
    </div>
    </div>
    </body>
    </html>
    """)

print(f"Relatório HTML salvo em: {summary_report_html}")

# Salva o relatório CSV
with open(csv_report, "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(csv_data)

print(f"Relatório CSV salvo em: {csv_report}")

# Salva o relatório Excel
workbook.save(excel_report)
print(f"Relatório Excel salvo em: {excel_report}")

Scripts recomendados

Identificador de spam em Python

MsgCoder - Codificador de mensagens

Função para decriptar Base64 em string compactada

RT CRASH - "Quebrando" hash MD5, SHA1, SHA224, SHA256, SHA384 e SHA512

Mkpass - Função para gerar senhas aleatórias


  

Comentários
[1] Comentário enviado por maurixnovatrento em 11/10/2024 - 12:54h

MUITO BOM.
______________________________________________________________________
Inscreva-se no meu Canal: https://www.youtube.com/@LinuxDicasPro
Repositório GitHub do Canal: https://github.com/LinuxDicasPro
Grupo do Telegram: https://t.me/LinuxDicasPro
Meu GitHub Pessoal: https://github.com/mxnt10


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts