write me an python program that uses nmap to scan opened services, with scripts and uses subfinder, httpx, nuclei like "subfinder -d <domain_to_scan> -silent | httpx | nuclei -as" and scans all specified domains. IPs and domains are stored in mongodb, all previous scans result aslo stored in mongo db. Every scan script should check differences of opened services and vulnerabilities. After scan and comparison with previous result script should generate pdf with all results with company logo on top of every page, report should be colorized, pretty with some icons and good enterprise font. And after generating report it should be send to client, with telegram id specified in mongodb (where IPs, and domains stored, previous results).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, this is a substantial project. I'll provide a Python framework and outline the key components. Due to the complexity and reliance on external tools, this will be a high-level guide with code snippets. You'll need to fill in the details, handle error conditions, and adapt it to your specific environment.
Important Considerations:
Legality: Scanning networks without permission is illegal. Ensure you have explicit authorization before running this script.
Dependencies: You'll need to install nmap, subfinder, httpx, nuclei, pymongo, reportlab, and a Telegram bot library.
Error Handling: Robust error handling is crucial. The script should gracefully handle failures of external tools, network issues, and MongoDB operations.
Rate Limiting: Be mindful of rate limits when using external services (like Telegram).
Security: Store sensitive information (like MongoDB credentials and Telegram bot tokens) securely. Do not hardcode them in the script. Use environment variables or a configuration file.
Scalability: For large numbers of domains, consider using a task queue (e.g., Celery) to distribute the scanning workload.
import os
MONGODB_URI = os.environ.get("MONGODB_URI", "mongodb://localhost:27017/")
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
COMPANY_LOGO_PATH = "company_logo.png" # Replace with your logo path
FONT_NAME = "Helvetica" # Or another enterprise-grade font
3. db_manager.py
python
from pymongo import MongoClient
from config import MONGODB_URI
client = MongoClient(MONGODB_URI)
db = client.security_scans # Or your preferred database name
def store_scan_result(domain, ip, scan_data):
"""Stores scan results in MongoDB."""
result = {
"domain": domain,
"ip": ip,
"scan_data": scan_data,
"timestamp": datetime.datetime.now()
}
db.scan_results.insert_one(result)
def get_previous_scan_result(domain):
"""Retrieves the previous scan result for a domain."""
result = db.scan_results.find_one({"domain": domain}, sort=[("_id", pymongo.DESCENDING)])
return result
def get_domain_telegram_id(domain):
"""Retrieves the Telegram ID associated with a domain."""
domain_info = db.domains.find_one({"domain": domain})
if domain_info and "telegram_id" in domain_info:
return domain_info["telegram_id"]
else:
return None
4. scanner.py
python
import subprocess
import nmap
import datetime
def run_subfinder(domain):
"""Runs Subfinder to discover subdomains."""
try:
result = subprocess.check_output(["subfinder", "-d", domain, "-silent"], text=True)
return result.splitlines()
except subprocess.CalledProcessError as e:
print(f"Subfinder error: {e}")
return []
def run_httpx(subdomains):
"""Runs httpx to enumerate HTTP endpoints."""
try:
# Construct the httpx command
command = ["httpx", "-threads", "50"] + subdomains
result = subprocess.check_output(command, text=True)
return result
except subprocess.CalledProcessError as e:
print(f"Httpx error: {e}")
return ""
def run_nuclei(targets):
"""Runs Nuclei to scan for vulnerabilities."""
try:
command = ["nuclei", "-as", "-u", ",".join(targets)]
result = subprocess.check_output(command, text=True)
return result
except subprocess.CalledProcessError as e:
print(f"Nuclei error: {e}")
return ""
def run_nmap(ip):
"""Runs Nmap to scan for open ports and services."""
nm = nmap.PortScanner()
try:
nm.scan(ip, arguments='-sV -T4 -F') # Service version detection, faster scan
return nm.all_hosts()
except nmap.PortScannerError as e:
print(f"Nmap error: {e}")
return {}
5. reporter.py
python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.colors import Color, HexColor
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, Image
from reportlab.lib.styles import getSampleStyleSheet
from config import COMPANY_LOGO_PATH, FONT_NAME
def generate_report(domain, previous_result, current_result, output_path):
"""Generates a PDF report with scan results."""
c = canvas.Canvas(output_path, pagesize=letter)
width, height = letter
# Add company logo
logo = Image(COMPANY_LOGO_PATH, width=2 * inch, height=0.5 * inch)
logo.drawOnCanvas(c, 20, height - 30)
# Styles
styles = getSampleStyleSheet()
title_style = styles['Heading1']
normal_style = styles['Normal']
# Report Title
c.setFont(FONT_NAME, 24)
c.setFillColor(HexColor("#003366")) # Example color
c.drawString(50, height - 50, f"Security Scan Report - {domain}")
# Add sections for previous and current results
y_position = height - 100
# Previous Results
c.setFont(FONT_NAME, 16)
c.setFillColor(HexColor("#006699"))
c.drawString(50, y_position, "Previous Scan Results:")
y_position -= 20
c.setFont(FONT_NAME, 12)
c.setFillColor(Color(0, 0, 0))
if previous_result:
# Format and add previous results to the report
# ... (Implement formatting and adding of previous results)
pass
else:
c.drawString(50, y_position, "No previous scan results found.")
# Current Results
y_position -= 40
c.setFont(FONT_NAME, 16)
c.setFillColor(HexColor("#006699"))
c.drawString(50, y_position, "Current Scan Results:")
y_position -= 20
c.setFont(FONT_NAME, 12)
c.setFillColor(Color(0, 0, 0))
if current_result:
# Format and add current results to the report
# ... (Implement formatting and adding of current results)
pass
else:
c.drawString(50, y_position, "No current scan results found.")
c.save()
6. telegram_sender.py
python
import telegram
from config import TELEGRAM_BOT_TOKEN
bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
def send_report(telegram_id, report_path):
"""Sends the report to the specified Telegram ID."""
try:
with open(report_path, 'rb') as f:
bot.send_document(chat_id=telegram_id, document=f)
except Exception as e:
print(f"Telegram error: {e}")
7. main.py
python
import datetime
from scanner import run_subfinder, run_httpx, run_nuclei, run_nmap
from db_manager import store_scan_result, get_previous_scan_result, get_domain_telegram_id
from reporter import generate_report
from telegram_sender import send_report
def main():
domains = ["example.com", "anotherdomain.net"] # Replace with your domains
for domain in domains:
print(f"Scanning {domain}...")
# 1. Subdomain Enumeration
subdomains = run_subfinder(domain)
print(f"Found {len(subdomains)} subdomains.")
# 2. HTTP Enumeration
httpx_results = run_httpx(subdomains)
print("HTTP Enumeration completed.")
# 3. Vulnerability Scanning
nuclei_results = run_nuclei(subdomains)
print("Vulnerability Scanning completed.")
# 4. IP Resolution (Example - you'll need a more robust method)
try:
import socket
ip = socket.gethostbyname(domain)
except socket.gaierror:
ip = "Could not resolve IP"
# 5. Nmap Scan
nmap_results = run_nmap(ip)
print("Nmap Scan completed.")
# 6. Store Results
scan_data = {
"subdomains": subdomains,
"httpx_results": httpx_results,
"nuclei_results": nuclei_results,
"nmap_results": nmap_results
}
store_scan_result(domain, ip, scan_data)
# 7. Compare with Previous Results
previous_result = get_previous_scan_result(domain)
# 8. Generate Report
report_path = f"report_{domain}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
generate_report(domain, previous_result, scan_data, report_path)
# 9. Send Report via Telegram
telegram_id = get_domain_telegram_id(domain)
if telegram_id:
send_report(telegram_id, report_path)
print(f"Report sent to Telegram ID: {telegram_id}")
else:
print("Telegram ID not found for this domain.")
if __name__ == "__main__":
main()
8. requirements.txt
code
pymongo
reportlab
python-nmap
Key Improvements and Next Steps:
Detailed Reporting: The reporter.py needs significant work to format the scan results nicely in the PDF. Use ReportLab's features for tables, lists, and styling.
Difference Analysis: Implement logic to compare previous_result and current_result to highlight changes in open ports, services, and vulnerabilities.
Error Handling: Add try...except blocks around all external tool calls and database operations.
Configuration: Use a configuration file (e.g., YAML or JSON) to store settings instead of environment variables.
Logging: Implement logging to track the script's execution and errors.
Task Queue: For scalability, integrate a task queue like Celery.
IP Resolution: Improve IP resolution to handle multiple IPs per domain.
Data Validation: Validate the data received from external tools.
Security: Securely store credentials and handle sensitive data.
This is a complex undertaking. Start with a small subset of functionality and gradually add features. Test thoroughly at each step. Remember to prioritize security and legality. Good luck!