Automação de scan de vulnerabilidades de URL

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

[ Hits: 262 ]

Download vm_url.py




Automação de scan de vulnerabilidades de URL

  



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 uma URL
def scan_url(url):
    with tempfile.NamedTemporaryFile(delete=False) as nmap_output:
        nmap_cmd = f"nmap -sV -O -R --script nmap-vulners/ --open -Pn -oN {nmap_output.name} {url}"
        output, return_code = run_command(nmap_cmd)

    html_content = f"<h2>Resultados do Scan para {url}</h2><table><thead><tr><th>Porta</th><th>Serviço</th><th>Versão</th><th>Vulnerabilidade</th><th>Criticidade</th><th>Exploit Disponível</th></tr></thead><tbody>"
    
    host_score = 0
    total_ports = 0
    total_vulnerabilities = 0
    total_exploits = 0

    os_version = "N/A"
    hostname = "N/A"

    if return_code == 0:
        with open(nmap_output.name, "r") as output_file:
            for line in output_file:
                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>"
                        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()

                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("-", "_")
                        score = vuln_match.group(2)
                        link = vuln_match.group(3)
                        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>"
                        total_vulnerabilities += 1
                        host_score += 1

                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>"
                        total_exploits += 1
                        host_score += 10

        html_content += f"</tbody></table><p><strong>Sistema Operacional:</strong> {os_version}<br><strong>Nome do Host:</strong> {hostname}<br><strong>Quantidade de Portas Abertas:</strong> {total_ports}<br><strong>Quantidade de Vulnerabilidades:</strong> {total_vulnerabilities}<br><strong>Exploits Encontrados:</strong> {total_exploits}</p><hr>"
        return html_content, host_score, total_ports, total_vulnerabilities, total_exploits
    else:
        return f"<h2>Falha no scan para {url}</h2><p>Código de retorno: {return_code}</p><hr>", 0, 0, 0, 0

# 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')

# Lista de URLs
urls_to_scan = [
    "exemplo.com.br",
    "exemplo2.com.br",
    "ftp.exemplo.com.br",
    "gitlab.exemplo.com.br"
]

# Diretório para salvar os relatórios
report_dir = "/home/<Seu Usuario>/Desktop/VM"
if not os.path.exists(report_dir):
    os.makedirs(report_dir)

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")

html_content = """
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Relatório de Scan</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }
        h1 {
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        th, td {
            padding: 10px;
            text-align: left;
            border: 1px solid #ddd;
        }
        th {
            background-color: #4CAF50;
            color: white;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        p {
            font-size: 14px;
            color: #555;
        }
        hr {
            border: 0;
            height: 1px;
            background-color: #ccc;
            margin: 20px 0;
        }
    </style>
</head>
<body>
<h1>Relatório de Scan de Rede</h1>
"""

csv_data = [["Host", "Porta", "Serviço", "Versão", "Vulnerabilidade", "Criticidade", "Exploit Disponível", "Score Total"]]

if not os.path.exists(excel_report):
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "Histórico de Scans"
    sheet.append(["Host", "Data/Hora", "Portas Abertas", "Vulnerabilidades", "Exploits", "Score Total"])
else:
    workbook = openpyxl.load_workbook(excel_report)
    sheet = workbook.active

# Processa os resultados do scan de cada URL em paralelo
with ProcessPoolExecutor() as executor:
    future_to_url = {executor.submit(scan_url, url): url for url in urls_to_scan}
    for future in as_completed(future_to_url):
        url = future_to_url[future]
        try:
            html_result, score, total_ports, total_vulnerabilities, total_exploits = future.result()
            html_content += html_result
            sheet.append([url, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), total_ports, total_vulnerabilities, total_exploits, score])
        except Exception as e:
            print(f"Erro ao processar a URL {url}: {e}")
            html_content += f"<h2>Erro ao processar a URL {url}</h2><p>{str(e)}</p><hr>"

html_content += "</body></html>"

# Salva o relatório HTML
with open(summary_report_html, "w") as f:
    f.write(html_content)

# Salva o CSV
with open(csv_report, mode='w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(csv_data)

# Salva o Excel
workbook.save(excel_report)

print(f"Relatório HTML salvo em: {summary_report_html}")
print(f"Relatório CSV salvo em: {csv_report}")
print(f"Histórico de scans salvo em: {excel_report}")


Scripts recomendados

Scan de vulnerabilidade .sh

Identificador de spam em Python

DSearch - (Dir Search): script python para descobrir diretórios de servidores.

Adivinhar Número

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


  

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