diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..8d9c2c85fa12b30da89b8d02cd8dedf226352ca0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,64 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/*
+!downloads/.gitkeep
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# Environment variables
+.env
+.env.local
+config.py
+
+# Virtual Environments
+venv/
+env/
+ENV/
+env.bak/
+venv.bak/
+
+# Streamlit
+.streamlit/
+
+# OSINT output data
+reports/*
+!reports/.gitkeep
+maigret_reports/*
+!maigret_reports/.gitkeep
+
+# Ad-hoc scripts & unmanaged files
+Site_extract.py
+multi_comptes.py
+Dashboard_Ba7ath.bat
+1.13.0
+4.28.0
+exports/
+*.csv
+*.json
+!output.json
+*.log
+!fb_cookies.json
+*.jpg
+*.png
\ No newline at end of file
diff --git a/Ba7ath.spec b/Ba7ath.spec
new file mode 100644
index 0000000000000000000000000000000000000000..b8b97c3a1d0798b076489f0965f677f957fdb1fe
--- /dev/null
+++ b/Ba7ath.spec
@@ -0,0 +1,81 @@
+# -*- mode: python ; coding: utf-8 -*-
+import os
+from PyInstaller.utils.hooks import copy_metadata
+
+datas = [
+ ('dashboard.py', '.'),
+ ('pages', 'pages'),
+ ('assets', 'assets'),
+ ('output.json', '.'),
+ ('logo.png', '.'),
+ ('face_to_search.jpg', '.'),
+ ('favicon.ico', '.'),
+ ('spectre_modules', 'spectre_modules'),
+]
+
+# Copie des métadonnées Streamlit (indispensable)
+datas += copy_metadata('streamlit')
+
+import streamlit
+streamlit_path = os.path.dirname(streamlit.__file__)
+datas.append((os.path.join(streamlit_path, 'static'), 'streamlit/static'))
+
+# Copie des outils externes dans le sous-dossier outils_externes
+datas += [
+ ('sherlock', 'outils_externes/sherlock'),
+ ('spiderfoot', 'outils_externes/spiderfoot'),
+ ('Social-Finder', 'outils_externes/Social-Finder'),
+]
+
+import glob
+pages_scripts = glob.glob('pages/*.py')
+spectre_scripts = glob.glob('spectre_modules/*.py')
+analysis_scripts = ['run_app.py', 'dashboard.py'] + pages_scripts + spectre_scripts
+
+a = Analysis(
+ analysis_scripts,
+ pathex=[],
+ binaries=[],
+ datas=datas,
+ hiddenimports=[
+ 'config',
+ 'streamlit',
+ 'streamlit.runtime.scriptrunner.magic_funcs'
+ ],
+ hookspath=[],
+ hooksconfig={},
+ runtime_hooks=[],
+ excludes=['torch', 'tensorflow', 'tensorboard'],
+ noarchive=False,
+ optimize=0,
+)
+pyz = PYZ(a.pure)
+
+exe = EXE(
+ pyz,
+ a.scripts,
+ [],
+ exclude_binaries=True,
+ name='Ba7ath',
+ debug=False,
+ bootloader_ignore_signals=False,
+ strip=False,
+ upx=False,
+ console=True, # Laisse la console ouverte pour voir les erreurs, peut être mis à False pour prod
+ disable_windowed_traceback=False,
+ argv_emulation=False,
+ target_arch=None,
+ codesign_identity=None,
+ entitlements_file=None,
+ icon='favicon.ico'
+)
+
+coll = COLLECT(
+ exe,
+ a.binaries,
+ a.datas,
+ strip=False,
+ upx=False,
+ upx_exclude=[],
+ name='Ba7ath',
+)
diff --git a/Ba7ath_Installer.iss b/Ba7ath_Installer.iss
new file mode 100644
index 0000000000000000000000000000000000000000..a39279f4a3a8bb4c036eff4dd131c8e0d59f7ad4
--- /dev/null
+++ b/Ba7ath_Installer.iss
@@ -0,0 +1,18 @@
+[Setup]
+AppName=Ba7ath OSINT Suite
+AppVersion=1.0
+DefaultDirName={autopf}\Ba7ath OSINT Suite
+DefaultGroupName=Ba7ath OSINT Suite
+OutputDir=Output
+OutputBaseFilename=Installation_Ba7ath
+Compression=lzma2
+SolidCompression=yes
+SetupIconFile=dist\Ba7ath\favicon.ico
+UninstallDisplayIcon={app}\Ba7ath.exe
+
+[Files]
+Source: "dist\Ba7ath\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
+
+[Icons]
+Name: "{group}\Ba7ath OSINT Suite"; Filename: "{app}\Ba7ath.exe"
+Name: "{autodesktop}\Ba7ath OSINT Suite"; Filename: "{app}\Ba7ath.exe"
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..4319ebdd66844d8f1a11ac1a9a5d4798598cd0c2
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,32 @@
+FROM python:3.11-slim
+
+# Mettre à jour les paquets système et installer les dépendances pour la compilation C++ (face_recognition / dlib)
+RUN apt-get update && apt-get install -y \
+ cmake \
+ libgl1-mesa-glx \
+ build-essential \
+ git \
+ && rm -rf /var/lib/apt/lists/*
+
+# Créer un utilisateur non root (Recommandé par Hugging Face pour des raisons de sécurité)
+RUN useradd -m -u 1000 user
+
+# Définir le répertoire de travail
+WORKDIR /app
+
+# Copier et installer les dépendances Python
+COPY --chown=user:user requirements.txt .
+RUN pip install --no-cache-dir --upgrade pip && \
+ pip install --no-cache-dir -r requirements.txt
+
+# Copier tout le reste du projet
+COPY --chown=user:user . .
+
+# Basculer sur le nouvel utilisateur
+USER user
+
+# Exposer le port par défaut de Hugging Face
+EXPOSE 7860
+
+# Démarrer Streamlit sur le port 7860
+CMD ["streamlit", "run", "dashboard.py", "--server.port=7860", "--server.address=0.0.0.0"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8b0f0ec6647c2981c9256d06b9f100d3aa06794b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,11 @@
+---
+title: Ba7ath OSINT Suite
+emoji: 🕵️♂️
+colorFrom: blue
+colorTo: purple
+sdk: docker
+pinned: false
+---
+
+# Ba7ath OSINT Suite
+Tableau de bord pour OSINT.
diff --git a/README_BREVET_DASHBOARD.md b/README_BREVET_DASHBOARD.md
new file mode 100644
index 0000000000000000000000000000000000000000..a6b87de22b2fc3b7ec86f5d024407e94263aeadc
--- /dev/null
+++ b/README_BREVET_DASHBOARD.md
@@ -0,0 +1,41 @@
+# 🛡️ Ba7ath OSINT Suite (Dashboard) — Note de Dépôt de Propriété Intellectuelle (Brevet)
+
+## 1. Description Générale du Projet
+**Ba7ath OSINT Suite** est un tableau de bord analytique et d'investigation unifié (Dashboard), développé en Python (Streamlit). Il centralise et orchestre 16 modules spécialisés dans l'acquisition de renseignements en sources ouvertes (OSINT).
+
+Sa proposition de valeur réside dans la fusion d'outils disparates (recherche de pseudos, reconnaissance faciale, dorking automatisé) au sein d'une **interface unique et souveraine**. Toutes les investigations s'exécutent localement, garantissant qu'aucune donnée de recherche ne fuite vers des serveurs tiers centralisés.
+
+---
+
+## 2. Innovations Technologiques & Particularités (Revendications Brevetables)
+
+### 2.1. Moteur Algorithmique de "Dorking" Social Multilingue (Module Facebook Dorking)
+Contrairement aux outils de recherche classiques, ce module automatise la création d'opérateurs de recherche complexes (Google Dorks) spécifiquement optimisés pour l'architecture de Facebook.
+- **Génération Dynamique de Requêtes** : L'algorithme compile des opérateurs (`site:`, `intext:`, `inurl:`, `filetype:`) en combinant inclusions et exclusions heuristiques.
+- **Support RTL (Right-to-Left) Natif** : Traitement et encodage spécifiques pour la langue Arabe, vitaux pour l'investigation ciblée, préservant la structure bidirectionnelle lors de l'appel aux API.
+- **Scraping "Full-Content" Anti-Troncature** : Pour contourner la limite de 160 caractères imposée par l'API de Google, le système intègre un scraper furtif qui va lire le DOM de la page Facebook ciblée (paradigmes de fallback multiples : `data-ad-preview`, `userContent`, spans RTL) pour extraire l'intégralité du texte du post, tout en évitant les blocages.
+
+### 2.2. Pipeline de Reconnaissance Faciale & Reverse-Search (FaceFinder OSINT)
+Une chaîne de traitement hybride (Edge + Cloud-API) pour l'investigation sur des individus :
+1. **Détection Biométrique Locale** : Utilisation du package `face_recognition` pour détecter, dénombrer et annoter visuellement les visages sur une photographie avant tout envoi externe.
+2. **Résolution OpenGraph Miniature (Thumbnail Resolution)** : Lorsque les API de Reverse Image Search (SerpApi, Zenserp) retournent des liens de pages web sans lien direct vers l'image, le système interroge dynamiquement les balises OpenGraph (`og:image`, `twitter:image`) pour extraire la miniature haute résolution, offrant un gain de temps majeur à l'analyste.
+3. **Quota Manager Intégré** : Un gestionnaire local (`reverse_api_counts.json`) qui surveille et route intelligemment les requêtes vers différentes API en fonction des quotas gratuits restants, évitant les interruptions de service (Rate-Limiting).
+
+### 2.3. Hub d'Empreinte Numérique (Multi-Comptes OSINT)
+- **Orchestration Multi-Threads** : Le système exécute de concert plusieurs moteurs de recherche d'empreinte (comme Sherlock scannant plus de 474 plateformes, et SocialScan) pour vérifier la disponibilité ou l'occupation d'un pseudonyme.
+- **Normalisation des Données** : Les sorties non-structurées de la ligne de commande (stdout) de divers utilitaires CLI sont parsées via Regex et unifiées dans un modèle de données cohérent (Pandas DataFrame) pour générer des rapports exportables (CSV).
+
+### 2.4. Architecture Modulaire de type "Plug & Play"
+- Le framework a été pensé pour que chaque module (WaybackURLs, Domain Intel, YouTube, EmailHarvester, etc.) soit isolé techniquement mais partage le même écosystème de reporting et de gestion des identifiants (API Keys gérées côté client).
+
+---
+
+## 3. Architecture Technique Décrite
+- **Frontend / UI** : Développé via le framework Streamlit, offrant une interface réactive (*responsive*) optimisée avec des composants CSS personnalisés pour harmoniser l'expérience utilisateur (UX).
+- **Backend / Orchestrateur** : Python 3.x gérant les appels asynchrones, le parsing (BeautifulSoup, Regex) et le routage des processus (subprocess) vers des outils OSINT externes.
+- **Stockage & Export** : Génération de matrices de données (DataFrames) exportées nativement en JSON et CSV, stockées en local dans un dossier `reports/` sécurisé.
+
+## 4. Cas d'Usage & Applicabilité Industrielle
+- Veille Stratégique et e-Réputation : Traçabilité des mentions sociales, fuites de données (Leaks) ou usurpation d'identité sur les réseaux.
+- Investigations Journalistiques : Recherche croisée sur des pages officielles, détection d'avatars et profils fantômes.
+- Audits de Cybersécurité : Récolte d'informations en phase de reconnaissance (Footprinting) sur des domaines, adresses emails et sous-domaines.
diff --git a/Social-Finder/Dockerfile b/Social-Finder/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..b6c506e507dbac4c216e2b738ea4a7cbb79582d5
--- /dev/null
+++ b/Social-Finder/Dockerfile
@@ -0,0 +1,14 @@
+FROM python:3.12-alpine
+
+WORKDIR /app
+
+# Sherlock viene installato da Git → serve git
+RUN apk add --no-cache git
+
+COPY backend/requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+COPY backend .
+EXPOSE 3000
+
+CMD ["python", "app.py"]
diff --git a/Social-Finder/README.md b/Social-Finder/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..38d9feae1a7b606c77e1dd93564b519a0fc9faf0
--- /dev/null
+++ b/Social-Finder/README.md
@@ -0,0 +1,121 @@
+
+# 🔎 Social Finder
+
+
+
+
+
+
+
+[](https://sfinder.mattiapasti.com)
+
+---
+
+## 📌 Overview
+
+**Social Finder** is an **OSINT web application** built with **Flask** and powered by [Sherlock](https://github.com/sherlock-project/sherlock).
+It allows you to **search for a username across hundreds of social networks** and get structured results in a modern web interface.
+
+The project is fully containerized with **Docker** and production-ready with **Gunicorn**.
+
+---
+
+## ✨ Features
+
+- 🌐 Search usernames across multiple platforms (GitHub, Twitter, Instagram, etc.)
+- 📊 Clear and modern dashboard interface
+- 🐳 Docker-ready setup (easy deployment)
+- 🔒 Privacy-focused, no data stored
+- ⚡ Fast & concurrent checks using Sherlock
+
+---
+
+## 🛠 Tech Stack
+
+- **Backend:** Python, Flask, Gunicorn
+- **Frontend:** HTML, CSS, Vanilla JS
+- **OSINT Engine:** Sherlock
+- **Deployment:** Docker & Docker Compose
+
+---
+
+## 🚀 Getting Started
+
+### 🔧 Local Installation
+```bash
+# Clone the repository
+git clone https://github.com/MattiaPasti/Social-Finder.git
+cd social-finder/Social
+
+# Install dependencies
+pip install -r backend/requirements.txt
+
+# Run the app
+cd backend
+python app.py
+````
+
+App will run on: `http://localhost:5000`
+
+---
+
+### 🐳 Docker Setup
+
+```bash
+# Clone the repository
+git clone https://github.com/MattiaPasti/Social-Finder.git
+cd social-finder/Social
+
+# Build and run
+docker compose up --build
+```
+
+App will run on: `http://localhost:8000`
+
+---
+
+## 🌍 Live Demo
+
+You can test Social Finder directly at:
+👉 [**sfinder.mattiapasti.com**](https://sfinder.mattiapasti.com/)
+
+---
+
+## 📜 License
+
+This project is licensed under the **MIT License** – see the [LICENSE](LICENSE) file for details.
+
+---
+
+## 🤝 Contributing
+
+Contributions, issues, and feature requests are welcome!
+Feel free to open an [issue](https://github.com/MattiaPasti/social-finder/issues) or submit a pull request.
+
+---
+
+## 📌 Roadmap
+
+* [ ] Add PDF export of search results
+* [ ] Improve detection heuristics
+* [ ] Extend supported platforms
+* [ ] Add authentication layer for private instances
+
+---
+
+## 📸 Preview
+
+
+
+##
+
+
+
+##
+
+
+
+
+---
+
+> ⚡ Built with ❤️ for OSINT & Cybersecurity research.
diff --git a/Social-Finder/backend/app.py b/Social-Finder/backend/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..a66d8eff2e24cbddb02445b6c71fcfcc3f20ccb5
--- /dev/null
+++ b/Social-Finder/backend/app.py
@@ -0,0 +1,503 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Social Finder – API backend (optimized & stricter 404 handling)
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import signal
+import subprocess
+import time
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import dataclass
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from typing import Dict, Iterator, List, Sequence, Tuple
+from urllib.parse import urlparse
+
+import requests
+from bs4 import BeautifulSoup
+from ddgs import DDGS
+from flask import Flask, Response, jsonify, render_template, request
+from requests.adapters import HTTPAdapter, Retry
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Config
+# ──────────────────────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class Config:
+ USER_AGENT: str = "Mozilla/5.0 (SocialFinder)"
+ DUCK_RATE: float = float(os.getenv("DUCK_RATE", 0.25)) # sec tra query DDG
+ PAGE_TIMEOUT: int = int(os.getenv("PAGE_TIMEOUT", 8))
+ SHERLOCK_TIMEOUT: str = os.getenv("SHERLOCK_TIMEOUT", "5")
+ SCRAPE_WORKERS: int = int(os.getenv("SCRAPE_WORKERS", 10))
+ MAX_BODY_BYTES: int = int(os.getenv("MAX_BODY_BYTES", 20_480))
+ SERPAPI_KEY: str | None = os.getenv("SERPAPI_KEY")
+
+
+CFG = Config()
+
+INVALID_HTML_PATTERNS: set[str] = {
+ "sign in",
+ "log in",
+ "login required",
+ "you need to sign in",
+ "autenticati",
+ "registrati per continuare",
+ "captcha",
+ "devi essere loggato",
+ "area riservata",
+ "contenuto privato",
+ "restricted access",
+ "acesso restrito",
+ "accès restreint",
+ "404",
+ "page not found",
+ "error 404",
+ "error",
+ "not found",
+ "pagina non trovata",
+ "pagina non disponibile",
+ "we couldn't find",
+ "sorry, this page isn't",
+ "torna alla home",
+ "contenuto non disponibile",
+ "errore nel recupero della pagina",
+ "sito non trovato",
+ "nicht gefunden",
+ "pas trouv",
+ "no encontrada",
+ "не найдена",
+ "this page could not be found",
+ "la pagina che stavi cercando non è stata trovata",
+}
+
+ERROR_INDICATORS: tuple[str, ...] = (
+ "
404",
+ "page not found",
+ "error",
+ "pagina non trovata",
+ 'class="error',
+ 'class="notfound',
+ 'class="page-error',
+ 'class="404',
+ 'id="error',
+ 'id="notfound',
+ 'id="page-error',
+ 'id="404',
+ 'meta name="error"',
+ 'prerender-status-code" content="404',
+ "error-page",
+ "notfound-container",
+)
+
+HARSH_404_REGEX = re.compile(r"(404|not\s*found|pagina\s*non\s*trovata)", re.IGNORECASE)
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# LIMIT RATING REQUEST
+# ──────────────────────────────────────────────────────────────────────────────
+
+RATE_WINDOW = 5 * 60 # 5 minuti
+RATE_MAX = 1 # 1 richiesta per finestra
+_rate_lock = threading.Lock()
+_rate_hits = {} # { (route, ip): [t1, t2, ...] } timestamps secondi
+
+def client_ip():
+ # Se usi Proxy/Nginx/CF potresti voler leggere X-Forwarded-For
+ fwd = request.headers.get("X-Forwarded-For", "")
+ if fwd:
+ return fwd.split(",")[0].strip()
+ return request.remote_addr or "unknown"
+
+def rate_limit(route_key: str):
+ def decorator(fn):
+ def wrapper(*args, **kwargs):
+ ip = client_ip()
+ now = time.time()
+ key = (route_key, ip)
+ with _rate_lock:
+ hits = _rate_hits.get(key, [])
+ # tieni solo gli hit negli ultimi 5 min
+ hits = [t for t in hits if now - t < RATE_WINDOW]
+ if len(hits) >= RATE_MAX:
+ # 429 con messaggio coerente
+ if request.path == "/api/search-stream":
+ return Response(
+ "event: message\ndata: ⚠️ Limite raggiunto. Riprova tra 5 minuti.\n\n",
+ status=429,
+ mimetype="text/event-stream"
+ )
+ abort(429, description="Troppi tentativi. Riprova tra 5 minuti.")
+ hits.append(now)
+ _rate_hits[key] = hits
+ return fn(*args, **kwargs)
+ # preserva nome e docstring (opzionale)
+ wrapper.__name__ = fn.__name__
+ wrapper.__doc__ = fn.__doc__
+ return wrapper
+ return decorator
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# HTTP session (retry/backoff)
+# ──────────────────────────────────────────────────────────────────────────────
+
+
+def build_session() -> requests.Session:
+ sess = requests.Session()
+ sess.headers.update({"User-Agent": CFG.USER_AGENT})
+ retries = Retry(
+ total=2,
+ backoff_factor=0.3,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=("HEAD", "GET"),
+ respect_retry_after_header=True,
+ )
+ adapter = HTTPAdapter(max_retries=retries, pool_maxsize=CFG.SCRAPE_WORKERS)
+ sess.mount("http://", adapter)
+ sess.mount("https://", adapter)
+ return sess
+
+
+SESSION = build_session()
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Helpers
+# ──────────────────────────────────────────────────────────────────────────────
+
+
+def match_domain(url: str, wanted: str) -> bool:
+ host = (urlparse(url).hostname or "").lower()
+ return host == wanted or host.endswith("." + wanted)
+
+
+def build_username_variants(nome: str, cognome: str) -> list[str]:
+ nome, cognome = (re.sub(r"\W+", "", s.lower()) for s in (nome, cognome))
+ base = [
+ f"{nome}{cognome}",
+ f"{cognome}{nome}",
+ f"{nome}.{cognome}",
+ f"{nome}_{cognome}",
+ f"{nome[:1]}{cognome}" if nome else "",
+ f"{cognome}{nome[:1]}" if nome and cognome else "",
+ ]
+ extra = [f"{b}_" for b in base if b] + [f"{b}1" for b in base if b]
+ return sorted({v for v in base + extra if v})
+
+
+def sse(msg: str) -> str:
+ return f"data: {msg}\n\n"
+
+
+def stream_cmd(cmd: Sequence[str], label: str) -> Iterator[str]:
+ yield sse(f"▶️ {' '.join(cmd)}")
+ with subprocess.Popen(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
+ ) as proc:
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ yield sse(f"{label} | {line.rstrip()}")
+ yield sse(f"✅ {label} terminato (exit {proc.returncode})")
+
+
+def is_valid_page(url: str) -> Tuple[bool, str]:
+ """Controllo avanzato validità pagina. Più severo su 404/not found."""
+ if not url.lower().startswith(("http://", "https://")):
+ return False, "URL deve iniziare con http:// o https://"
+
+ try:
+ parsed = urlparse(url)
+ if not parsed.netloc:
+ return False, "URL non valido: dominio mancante"
+ except Exception as e:
+ return False, f"Errore parsing URL: {e}"
+
+ headers = {
+ "Accept": "text/html,*/*",
+ "Accept-Encoding": "identity",
+ "Range": f"bytes=0-{CFG.MAX_BODY_BYTES - 1}",
+ }
+
+ try:
+ resp = SESSION.head(
+ url,
+ headers=headers,
+ allow_redirects=True,
+ timeout=CFG.PAGE_TIMEOUT,
+ verify=True,
+ )
+ if resp.status_code in (405, 501): # HEAD non supportato
+ resp = SESSION.get(
+ url,
+ headers=headers,
+ allow_redirects=True,
+ timeout=CFG.PAGE_TIMEOUT,
+ stream=True,
+ )
+ if hasattr(resp, "raw") and resp.raw:
+ resp.raw.read(CFG.MAX_BODY_BYTES)
+ resp.close()
+
+ status = resp.status_code
+ if status == 200:
+ status_reason = "200 OK"
+ elif status in (202, 204):
+ return True, f"{status} Accepted/No Content"
+ elif status in (404, 410):
+ return False, f"HTTP Status {status} (hard fail)"
+ elif 300 <= status < 400:
+ return False, f"Redirect non risolto ({status})"
+ elif 400 <= status < 500:
+ return False, f"HTTP Client Error {status}"
+ else:
+ return False, f"HTTP Server Error {status}"
+
+ ctype = resp.headers.get("content-type", "").lower()
+ if "text/html" not in ctype:
+ return True, status_reason
+
+ raw = resp.content[: CFG.MAX_BODY_BYTES]
+ soup = BeautifulSoup(raw, "html.parser")
+ main = soup.find("main") or soup.find("body") or soup
+ text = main.get_text(separator=" ", strip=True).lower()
+ html_str = str(main)
+
+ if HARSH_404_REGEX.search(text):
+ return False, f"{status_reason} + text 404"
+ if any(p in text for p in INVALID_HTML_PATTERNS):
+ return False, f"{status_reason} + pattern visibile"
+
+ indicators_hit = [ind for ind in ERROR_INDICATORS if ind in html_str]
+ if any("404" in ind or "notfound" in ind for ind in indicators_hit):
+ return False, f"{status_reason} + html 404"
+ if len(indicators_hit) >= 2:
+ return False, f"{status_reason} + multiple error indicators"
+
+ if re.search(r" ]+(404|notfound|error)[^>]*>", html_str):
+ return False, f"{status_reason} + img 404"
+ if re.search(r'class=["\'][^"\']*(error|notfound|404)[^"\']*["\']', html_str):
+ return False, f"{status_reason} + class regex"
+
+ return True, status_reason
+
+ except requests.exceptions.TooManyRedirects:
+ return False, "Troppi redirect (loop?)"
+ except requests.exceptions.SSLError:
+ return False, "Errore SSL/Certificato"
+ except requests.exceptions.Timeout:
+ return False, "Timeout connessione"
+ except requests.exceptions.ConnectionError:
+ return False, "Errore di connessione"
+ except requests.exceptions.RequestException as e:
+ return False, f"Errore richiesta: {e}"
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Core search
+# ──────────────────────────────────────────────────────────────────────────────
+
+
+def search_dorks(fullname: str, seen: set[str]) -> List[str]:
+ targets = {
+ "facebook.com": f'"{fullname}" site:facebook.com',
+ "instagram.com": f'"{fullname}" site:instagram.com',
+ "linkedin.com": f'"{fullname}" site:linkedin.com',
+ "twitter.com": f'"{fullname}" site:twitter.com',
+ "tiktok.com": f'"{fullname}" site:tiktok.com',
+ "youtube.com": f'"{fullname}" site:youtube.com',
+ }
+
+ engine = "SerpAPI" if CFG.SERPAPI_KEY else "DuckDuckGo"
+ results: list[str] = []
+
+ for dom, query in targets.items():
+ try:
+ if CFG.SERPAPI_KEY:
+ data = SESSION.get(
+ "https://serpapi.com/search.json",
+ params={
+ "engine": "google",
+ "q": query,
+ "api_key": CFG.SERPAPI_KEY,
+ "num": 25,
+ },
+ timeout=15,
+ ).json()
+ raw_links = [
+ hit.get("link", "") for hit in data.get("organic_results", [])
+ ]
+ else:
+ with DDGS(proxy=None, timeout=10) as ddgs:
+ raw_links = [h["href"] for h in ddgs.text(query, max_results=40)]
+ time.sleep(CFG.DUCK_RATE)
+ except Exception:
+ raw_links = []
+
+ good = [u for u in raw_links if match_domain(u, dom) and u not in seen][:10]
+ results.extend(good)
+ seen.update(good)
+
+ return results
+
+
+def validate_links(urls: Sequence[str]) -> List[str]:
+ valid: list[str] = []
+ with ThreadPoolExecutor(max_workers=CFG.SCRAPE_WORKERS) as pool:
+ futs = {pool.submit(is_valid_page, u): u for u in urls}
+ for fut in as_completed(futs):
+ url = futs[fut]
+ ok, _ = fut.result()
+ if ok:
+ valid.append(url)
+ return valid
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Flask
+# ──────────────────────────────────────────────────────────────────────────────
+
+app = Flask(__name__, static_folder="static", static_url_path="/static")
+
+
+@app.route("/")
+# @rate_limit("main")
+def home():
+ return render_template("index.html")
+
+@app.route("/disclaimer")
+# @rate_limit("disclaimer")
+def disclaimer():
+ return render_template("disclaimer.html")
+
+@app.route("/privacy")
+# @rate_limit("privacy")
+def privacy():
+ return render_template("privacy.html")
+
+@app.route("/api/search-stream")
+# @rate_limit("search-stream")
+def api_search_stream():
+ nome = request.args.get("nome", "").strip()
+ cognome = request.args.get("cognome", "").strip()
+ fullname = f"{nome} {cognome}".strip()
+ usernames = build_username_variants(nome, cognome)
+ t0 = time.time()
+
+ def generate() -> Iterator[str]:
+ yield sse(f"🔎 Avvio ricerca per: {fullname or '(nessun nome)'}")
+ yield sse(f"🧩 Username generati: {', '.join(usernames) or '(0)'}")
+
+ # 1) Sherlock
+ sherlock_links: Dict[str, List[str]] = {}
+ with TemporaryDirectory() as tmp:
+ yield sse("⏳ Esecuzione Sherlock…")
+ cmd = [
+ "sherlock",
+ *usernames,
+ "--folderoutput",
+ tmp,
+ "--print-found",
+ "--timeout",
+ CFG.SHERLOCK_TIMEOUT,
+ ]
+ for chunk in stream_cmd(cmd, "sherlock"):
+ yield chunk
+ for u in usernames:
+ f = Path(tmp) / f"{u}.txt"
+ urls: list[str] = []
+ if f.exists():
+ for raw in f.read_text(encoding="utf-8").splitlines():
+ m = re.search(r"https?://\S+", raw)
+ if m:
+ urls.append(m.group(0))
+ sherlock_links[u] = sorted(set(urls))
+ yield sse(f"📦 {u}: {len(urls)} link trovati")
+
+ # dedup
+ all_links: list[str] = []
+ seen: set[str] = set()
+ for lst in sherlock_links.values():
+ for u in lst:
+ if u not in seen:
+ seen.add(u)
+ all_links.append(u)
+
+ # 2) Dorks
+ engine = "SerpAPI" if CFG.SERPAPI_KEY else "DuckDuckGo"
+ yield sse(f"⏳ Avvio dork con {engine}…")
+ dork_links = search_dorks(fullname, seen)
+ all_links.extend(dork_links)
+ yield sse(f"✅ {len(dork_links)} link validi dai dork")
+
+ # 3) Verifica
+ yield sse("⏳ Verifica validità link…")
+ valid_links: list[str] = []
+ with ThreadPoolExecutor(max_workers=CFG.SCRAPE_WORKERS) as pool:
+ futs = {pool.submit(is_valid_page, u): u for u in all_links}
+ for fut in as_completed(futs):
+ url = futs[fut]
+ ok, reason = fut.result()
+ if ok:
+ valid_links.append(url)
+ yield sse(f"🔗 {url} {'✅' if ok else '❌'} ({reason})")
+
+ yield sse(f"✅ Link validi totali: {len(valid_links)}")
+ payload = {
+ "ok": True,
+ "query": {"nome": nome, "cognome": cognome},
+ "links": valid_links,
+ }
+ elapsed = int(time.time() - t0)
+ yield sse(f"🎉 Ricerca terminata in {elapsed}s")
+ yield sse(json.dumps({"done": True, "result": payload}))
+
+ return Response(generate(), mimetype="text/event-stream")
+
+
+@app.route("/api/search")
+# @rate_limit("search")
+def api_search():
+ return jsonify({"ok": True, "links": []}), 200
+
+
+LINK_CACHE = {}
+
+
+@app.post("/api/link-check")
+# @rate_limit("link-check")
+def link_check():
+ data = request.get_json(force=True, silent=True) or {}
+ url = data.get("url")
+ if not url:
+ return jsonify({"error": "missing url"}), 400
+ if url in LINK_CACHE:
+ return jsonify(LINK_CACHE[url])
+
+ valid, reason = is_valid_page(url) # implementa la tua logica
+ resp = {"url": url, "valid": valid, "reason": reason}
+ LINK_CACHE[url] = resp
+ return jsonify(resp)
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Shutdown
+# ──────────────────────────────────────────────────────────────────────────────
+
+
+def _graceful_exit(*_):
+ raise SystemExit(0)
+
+
+signal.signal(signal.SIGINT, _graceful_exit)
+signal.signal(signal.SIGTERM, _graceful_exit)
+
+
+if __name__ == "__main__":
+ app.run("0.0.0.0", 3000, debug=True)
diff --git a/Social-Finder/backend/requirements.txt b/Social-Finder/backend/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8d33e9d242e101e1cb84452d1b7cf361965420aa
--- /dev/null
+++ b/Social-Finder/backend/requirements.txt
@@ -0,0 +1,5 @@
+Flask==3.0.2
+ddgs==9.4.0
+sherlock-project @ git+https://github.com/sherlock-project/sherlock.git
+requests==2.32.3
+beautifulsoup4==4.13.4
\ No newline at end of file
diff --git a/Social-Finder/backend/static/css/styles.css b/Social-Finder/backend/static/css/styles.css
new file mode 100644
index 0000000000000000000000000000000000000000..c9359e3b12aa50904fd0309c4bfb95a3884cecad
--- /dev/null
+++ b/Social-Finder/backend/static/css/styles.css
@@ -0,0 +1,322 @@
+/* ============================================================================
+ * Social Finder – Custom CSS
+ * ==========================================================================*/
+
+/* Utility override */
+.hidden {
+ display: none !important;
+}
+
+/* --------------------------- RESULTS GRID ---------------------------------*/
+.results-container {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
+ gap: 1rem;
+}
+
+/* --------------------------- PROFILE CARD ---------------------------------*/
+.profile-card {
+ background: rgba(255, 255, 255, 0.9);
+ backdrop-filter: blur(6px);
+ border-radius: 1rem;
+ box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ transition: transform .12s ease, box-shadow .12s ease;
+}
+
+.profile-card:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 12px 28px rgba(0, 0, 0, 0.09);
+}
+
+/* Header */
+.card-header {
+ display: flex;
+ align-items: center;
+ gap: .8rem;
+ padding: 1rem 1.25rem .8rem;
+ border-bottom: 1px solid #e2e8f0;
+}
+
+.platform-icon {
+ width: 32px;
+ height: 32px;
+ border-radius: .5rem;
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ font-size: 1.1rem;
+}
+
+.platform-info h3 {
+ font-weight: 600;
+ font-size: 1.05rem;
+ margin: 0;
+ color: #1e293b;
+}
+
+.platform-info p {
+ margin: .1rem 0 0;
+ font-size: .8rem;
+ color: #475569;
+}
+
+.truncate {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* Body */
+.card-body {
+ padding: .9rem 1.25rem 1.1rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: .5rem;
+}
+
+.btn {
+ background: #6366f1;
+ color: white;
+ font-size: .85rem;
+ padding: .45rem .9rem;
+ border-radius: .65rem;
+ display: inline-flex;
+ align-items: center;
+ gap: .35rem;
+ text-decoration: none;
+ transition: background .12s ease, transform .12s ease;
+}
+
+.btn:hover {
+ background: #4f46e5;
+ transform: scale(.98);
+}
+
+.validation-badge,
+.status-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: .32rem;
+ font-size: .72rem;
+ font-weight: 500;
+ padding: .18rem .55rem;
+ border-radius: .6rem;
+ letter-spacing: .02em;
+}
+
+.status-badge.valid,
+.validation-badge.valid {
+ background: #dcfce7;
+ color: #166534;
+}
+
+.status-badge.invalid,
+.validation-badge.invalid {
+ background: #fee2e2;
+ color: #991b1b;
+}
+
+.status-badge.pending,
+.validation-badge.unknown {
+ background: #e2e8f0;
+ color: #475569;
+}
+
+.reason {
+ font-size: .7rem;
+ color: #64748b;
+ margin-left: .2rem;
+}
+
+/* Console */
+#console {
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-size: .8rem;
+}
+
+#console-container {
+ border-radius: 1rem;
+ overflow: hidden;
+}
+
+/* Loader inline */
+.loading-spinner {
+ width: 48px;
+ height: 48px;
+ border: 4px solid #cbd5e1;
+ border-top-color: #6366f1;
+ border-radius: 50%;
+ animation: spin 0.9s linear infinite;
+}
+
+/* Overlay spinner */
+.spinner-xl {
+ width: 70px;
+ height: 70px;
+ border: 6px solid rgba(0, 0, 0, 0.1);
+ border-top-color: #6366f1;
+ border-radius: 50%;
+ animation: spin 0.9s linear infinite;
+}
+
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+/* Toggle dettagli: nasconde il corpo delle card */
+#cards.details-hidden .card-body {
+ display: none;
+}
+
+/* Mini animazione ingresso */
+.fade-in {
+ opacity: 0;
+ transform: translateY(8px);
+ animation: fadeInUp 0.25s ease forwards;
+}
+
+@keyframes fadeInUp {
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+/* Platform icon colors (solo alcune, il resto via Tailwind/brand) */
+.platform-icon.facebook {
+ background: #1877f2;
+}
+
+.platform-icon.instagram {
+ background: #e1306c;
+}
+
+.platform-icon.twitter,
+.platform-icon.x {
+ background: #000000;
+}
+
+.platform-icon.linkedin {
+ background: #0a66c2;
+}
+
+.platform-icon.youtube {
+ background: #ff0000;
+}
+
+.platform-icon.tiktok {
+ background: #000000;
+}
+
+.platform-icon.github {
+ background: #24292e;
+}
+
+.platform-icon.gitlab {
+ background: #e24329;
+}
+
+.platform-icon.reddit {
+ background: #ff4500;
+}
+
+.platform-icon.spotify {
+ background: #1db954;
+}
+
+.platform-icon.soundcloud {
+ background: #ff7700;
+}
+
+.platform-icon.telegram {
+ background: #229ed9;
+}
+
+.platform-icon.vk {
+ background: #4c75a3;
+}
+
+.platform-icon.medium {
+ background: #00ab6c;
+}
+
+.platform-icon.pinterest {
+ background: #bd081c;
+}
+
+.platform-icon.tumblr {
+ background: #35465c;
+}
+
+.platform-icon.dribbble {
+ background: #ea4c89;
+}
+
+.platform-icon.behance {
+ background: #1769ff;
+}
+
+.platform-icon.generic {
+ background: #f1f5f9;
+ color: #64748b;
+}
+
+/* Reduce motion */
+@media (prefers-reduced-motion: reduce) {
+
+ .loading-spinner,
+ .spinner-xl {
+ animation: none;
+ }
+}
+
+/* Responsive tweaks */
+@media (max-width: 640px) {
+ .card-header {
+ padding: .8rem 1rem .6rem;
+ }
+
+ .platform-icon {
+ width: 28px;
+ height: 28px;
+ font-size: 1rem;
+ }
+
+ .platform-info h3 {
+ font-size: .95rem;
+ }
+
+ .card-body {
+ padding: .7rem 1rem .9rem;
+ }
+}
+
+/* Aggiungi questo in fondo al file */
+
+/* Fix per toggle dettagli - applica a tutte le card */
+#cards.details-hidden .profile-card .card-body {
+ display: none !important;
+}
+
+/* Stile per stato iniziale */
+#cards.details-hidden .card-body {
+ display: none;
+}
+
+.profile-card.collapsed .card-body {
+ display: none;
+}
+
+/* Mostra/Nascondi INTERA CARD */
+#cards.details-hidden .profile-card {
+ display: none !important;
+}
diff --git a/Social-Finder/backend/static/js/scripts.js b/Social-Finder/backend/static/js/scripts.js
new file mode 100644
index 0000000000000000000000000000000000000000..5cd20f3bd8d87cb4e08cba370148f5629f4063f2
--- /dev/null
+++ b/Social-Finder/backend/static/js/scripts.js
@@ -0,0 +1,538 @@
+/* ============================================================================
+ * Social Finder – Frontend JS (completo) – SSE + doppio toggle + no-results finale
+ * ==========================================================================*/
+
+/* ------------------------- CONFIG / COSTANTI ------------------------------*/
+const PLATFORM = {
+ "9gag.com": { icon: "ri-emotion-laugh-fill", brand: "9gag", label: "9GAG" },
+ "academia.edu": { icon: "ri-graduation-cap-fill", brand: "academia", label: "Academia.edu" },
+ "apple.com": { icon: "ri-apple-fill", brand: "apple", label: "Apple Discussions" },
+ "artstation.com": { icon: "ri-brush-fill", brand: "artstation", label: "ArtStation" },
+ "biggerpockets.com": { icon: "ri-home-4-fill", brand: "biggerpockets", label: "BiggerPockets" },
+ "boardgamegeek.com": { icon: "ri-gamepad-fill", brand: "bgg", label: "BoardGameGeek" },
+ "clubhouse.com": { icon: "ri-mic-fill", brand: "clubhouse", label: "Clubhouse" },
+ "codepen.io": { icon: "ri-code-fill", brand: "codepen", label: "CodePen" },
+ "cults3d.com": { icon: "ri-cube-fill", brand: "cults3d", label: "Cults3D" },
+ "deviantart.com": { icon: "ri-palette-fill", brand: "deviantart", label: "DeviantArt" },
+ "discord.com": { icon: "ri-discord-fill", brand: "discord", label: "Discord" },
+ "dribbble.com": { icon: "ri-ball-pen-fill", brand: "dribbble", label: "Dribbble" },
+ "drive2.ru": { icon: "ri-car-fill", brand: "drive2", label: "Drive2" },
+ "duolingo.com": { icon: "ri-translate-2", brand: "duolingo", label: "Duolingo" },
+ "eyeem.com": { icon: "ri-camera-3-fill", brand: "eyeem", label: "EyeEm" },
+ "facebook.com": { icon: "ri-facebook-fill", brand: "facebook", label: "Facebook" },
+ "freesound.org": { icon: "ri-volume-up-fill", brand: "freesound", label: "Freesound" },
+ "freelance.habr.com": { icon: "ri-briefcase-4-fill", brand: "habr", label: "Freelance Habr" },
+ "geocaching.com": { icon: "ri-compass-3-fill", brand: "geocaching", label: "Geocaching" },
+ "gitlab.com": { icon: "ri-gitlab-fill", brand: "gitlab", label: "GitLab" },
+ "gitlab.gnome.org": { icon: "ri-code-box-fill", brand: "gnome", label: "GNOME GitLab" },
+ "giphy.com": { icon: "ri-image-2-fill", brand: "giphy", label: "Giphy" },
+ "habr.com": { icon: "ri-terminal-window-fill", brand: "habr", label: "Habr" },
+ "houzz.com": { icon: "ri-paint-brush-fill", brand: "houzz", label: "Houzz" },
+ "hudsonrock.com": { icon: "ri-shield-user-fill", brand: "hudsonrock", label: "HudsonRock" },
+ "imgur.com": { icon: "ri-image-fill", brand: "imgur", label: "Imgur" },
+ "instagram.com": { icon: "ri-instagram-fill", brand: "instagram", label: "Instagram" },
+ "interPals.net": { icon: "ri-user-heart-fill", brand: "interpals", label: "InterPals" },
+ "kaskus.co.id": { icon: "ri-chat-3-fill", brand: "kaskus", label: "Kaskus" },
+ "kick.com": { icon: "ri-game-fill", brand: "kick", label: "Kick" },
+ "last.fm": { icon: "ri-music-fill", brand: "lastfm", label: "Last.fm" },
+ "livelib.ru": { icon: "ri-book-read-fill", brand: "livelib", label: "LiveLib" },
+ "linkedin.com": { icon: "ri-linkedin-fill", brand: "linkedin", label: "LinkedIn" },
+ "mixcloud.com": { icon: "ri-cloud-fill", brand: "mixcloud", label: "MixCloud" },
+ "myanimelist.net": { icon: "ri-emotion-happy-fill", brand: "myanimelist", label: "MyAnimeList" },
+ "mydramalist.com": { icon: "ri-film-fill", brand: "dramalist", label: "MyDramaList" },
+ "myspace.com": { icon: "ri-user-2-fill", brand: "myspace", label: "MySpace" },
+ "omg.lol": { icon: "ri-earth-fill", brand: "omg", label: "OMG.lol" },
+ "osu.ppy.sh": { icon: "ri-circle-fill", brand: "osu", label: "osu!" },
+ "periscope.tv": { icon: "ri-eye-fill", brand: "periscope", label: "Periscope" },
+ "reddit.com": { icon: "ri-reddit-fill", brand: "reddit", label: "Reddit" },
+ "roblox.com": { icon: "ri-cube-fill", brand: "roblox", label: "Roblox" },
+ "rumble.com": { icon: "ri-volume-down-fill", brand: "rumble", label: "Rumble" },
+ "scribd.com": { icon: "ri-book-mark-fill", brand: "scribd", label: "Scribd" },
+ "slideshare.net": { icon: "ri-slideshow-2-fill", brand: "slideshare", label: "SlideShare" },
+ "smule.com": { icon: "ri-mic-fill", brand: "smule", label: "Smule" },
+ "snapchat.com": { icon: "ri-snapchat-fill", brand: "snapchat", label: "Snapchat" },
+ "soundcloud.com": { icon: "ri-soundcloud-fill", brand: "soundcloud", label: "SoundCloud" },
+ "sporcle.com": { icon: "ri-question-fill", brand: "sporcle", label: "Sporcle" },
+ "spotify.com": { icon: "ri-spotify-fill", brand: "spotify", label: "Spotify" },
+ "starcitizen.com": { icon: "ri-rocket-2-fill", brand: "starcitizen", label: "Star Citizen" },
+ "steamcommunity.com": { icon: "ri-steam-fill", brand: "steam", label: "Steam" },
+ "strava.com": { icon: "ri-run-fill", brand: "strava", label: "Strava" },
+ "telegram.org": { icon: "ri-telegram-fill", brand: "telegram", label: "Telegram" },
+ "threads.net": { icon: "ri-at-line", brand: "threads", label: "Threads" },
+ "torretgalaxy.to": { icon: "ri-cloud-download-fill", brand: "torrentgalaxy", label: "TorrentGalaxy" },
+ "trello.com": { icon: "ri-layout-grid-fill", brand: "trello", label: "Trello" },
+ "ultimate-guitar.com": { icon: "ri-guitar-fill", brand: "ultimate-guitar", label: "Ultimate Guitar" },
+ "venmo.com": { icon: "ri-bank-card-fill", brand: "venmo", label: "Venmo" },
+ "vk.com": { icon: "ri-vk-fill", brand: "vk", label: "VK" },
+ "vsco.co": { icon: "ri-camera-fill", brand: "vsco", label: "VSCO" },
+ "weblate.org": { icon: "ri-translate-2", brand: "weblate", label: "Weblate" },
+ "wikipedia.org": { icon: "ri-book-open-fill", brand: "wikipedia", label: "Wikipedia" },
+ "xboxgamertag.com": { icon: "ri-game-fill", brand: "xbox", label: "Xbox Gamertag" },
+ "youtube.com": { icon: "ri-youtube-fill", brand: "youtube", label: "YouTube" }
+};
+
+const INVALID_HTML_PATTERNS = [
+ "page not found", "pagina non trovata", "pagina non disponibile",
+ "we couldn't find", "sorry, this page isn't", "sign in", "log in", "login required",
+ "autenticati", "error 404", "not found", "torna alla home"
+];
+
+/* ---------------------------- STATE ---------------------------------------*/
+const state = {
+ sherlockFinished: false,
+ pendingChecks: 0,
+ cardsCount: 0,
+ noResultTimer: null,
+ abortCtrl: null,
+ queue: [],
+ running: 0,
+ maxParallel: 5,
+ validCount: 0,
+ invalidCount: 0,
+ consoleVisible: false,
+ finishedFired: false
+};
+
+/* ---------------------------- DOM -----------------------------------------*/
+const form = document.querySelector("#searchForm") || document.querySelector("#search-form");
+const cardsContainer = document.querySelector("#cards") || document.querySelector("#cards-container");
+const loadingOverlay = document.querySelector("#loading-overlay");
+const loadingInline = document.querySelector("#loading-indicator");
+const noResultsEl = document.querySelector("#no-results");
+const consoleEl = document.querySelector("#console");
+const dashboardEl = document.getElementById('dashboard');
+const toggleConsoleBtn = document.getElementById('toggle-console');
+const toggleDetailsBtn = document.getElementById('toggle-details');
+const consoleContainer = document.getElementById('console-container');
+
+/* counters */
+const totalCountEl = document.getElementById('total-count');
+const validCountEl = document.getElementById('valid-count');
+const invalidCountEl = document.getElementById('invalid-count');
+const pendingCountEl = document.getElementById('pending-count');
+
+/* progress (se li usi) */
+const verifyBox = document.querySelector("#verify-progress");
+const vpDone = document.querySelector("#vp-done");
+const vpTotal = document.querySelector("#vp-total");
+
+/* ---------------------------- UTILS ---------------------------------------*/
+const htmlEscape = s =>
+ (s ?? "").replace(/[&<>"']/g, m =>
+ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[m])
+ );
+
+function resolvePlatform(host) {
+ const key = Object.keys(PLATFORM).find(d => host.endsWith(d));
+ if (key) return PLATFORM[key];
+ return { icon: "ri-link-m", brand: "generic", label: host.replace(/^www\./, "") };
+}
+
+function parseHost(url) { try { return new URL(url).hostname.toLowerCase(); } catch { return ""; } }
+
+function show(el) { el && el.classList.remove('hidden'); }
+function hide(el) { el && el.classList.add('hidden'); }
+
+function appendConsoleLine(text) {
+ if (!consoleEl) return;
+ consoleEl.textContent += text + "\n";
+ consoleEl.scrollTop = consoleEl.scrollHeight;
+}
+
+function showLoading(on) {
+ if (loadingOverlay) {
+ loadingOverlay.classList.toggle('hidden', !on);
+ } else if (loadingInline) {
+ loadingInline.classList.toggle('hidden', !on);
+ }
+}
+
+function updateDashboard() {
+ totalCountEl.textContent = state.cardsCount;
+ validCountEl.textContent = state.validCount;
+ invalidCountEl.textContent = state.invalidCount;
+ pendingCountEl.textContent = state.pendingChecks;
+ if (state.cardsCount > 0 || state.pendingChecks > 0) {
+ show(dashboardEl);
+ } else {
+ hide(dashboardEl);
+ }
+}
+
+function startVerification(total) {
+ if (!verifyBox) return;
+ vpTotal.textContent = total;
+ vpDone.textContent = 0;
+ verifyBox.classList.remove("hidden");
+}
+
+function tickVerification() {
+ if (!verifyBox) return;
+ vpDone.textContent = Number(vpDone.textContent) + 1;
+ if (vpDone.textContent === vpTotal.textContent) {
+ verifyBox.classList.add('hidden');
+ }
+}
+
+function cssEscape(str) { return str.replace(/(["'\\])/g, "\\$1"); }
+
+/* ---------------------------- STREAM --------------------------------------*/
+let evtSource = null;
+function startStream(params) {
+ stopStream();
+ const q = new URLSearchParams(params).toString();
+ evtSource = new EventSource(`/api/search-stream?${q}`);
+ showLoading(true);
+
+ evtSource.onmessage = e => {
+ const line = e.data;
+ if (!line) return;
+ appendConsoleLine(line);
+
+ // end signals
+ if (
+ line.includes("__SHERLOCK_DONE__") ||
+ line.includes('"done":true') ||
+ line.includes("✅ sherlock terminato") ||
+ line.startsWith("🎉 Ricerca terminata")
+ ) {
+ state.sherlockFinished = true;
+ finalizeIfDone();
+ }
+
+ // JSON payload finale
+ if (line.startsWith('{')) {
+ try {
+ const obj = JSON.parse(line);
+ if (obj?.result?.links?.length) {
+ addCards(obj.result.links);
+ }
+ } catch {/* ignore */ }
+ }
+
+ // "🔗 url ✅ (reason)"
+ if (line.startsWith('🔗 ')) {
+ const m = line.match(/^🔗\s+(\S+)\s+(✅|❌)\s+\((.+)\)$/);
+ if (m) {
+ const url = m[1];
+ const ok = m[2] === '✅';
+ const reason = m[3];
+
+ if (!cardsContainer.querySelector(`article[data-url="${CSS.escape(url)}"]`)) {
+ state.cardsCount++;
+ cardsContainer.appendChild(makeCard({ url }));
+ }
+
+ if (ok) {
+ state.validCount++;
+ setStatus(url, 'valid', reason);
+ } else {
+ state.invalidCount++;
+ setStatus(url, 'invalid', reason);
+ }
+
+ updateDashboard();
+ }
+ }
+ };
+
+ evtSource.onerror = () => {
+ appendConsoleLine("❌ Stream interrotto.");
+ state.sherlockFinished = true;
+ finalizeIfDone();
+ stopStream();
+ };
+}
+
+function stopStream() {
+ if (evtSource) { evtSource.close(); evtSource = null; }
+}
+
+/* ------------------------- LINK CHECK QUEUE -------------------------------*/
+function enqueueVerification(url) {
+ state.queue.push(url);
+ pumpQueue();
+ updateDashboard();
+}
+
+function pumpQueue() {
+ while (state.running < state.maxParallel && state.queue.length) {
+ const url = state.queue.shift();
+ state.running++;
+ state.pendingChecks++;
+ updateDashboard();
+
+ verifyLink(url, state.abortCtrl?.signal)
+ .catch(() => null)
+ .then(res => updateCard(url, res))
+ .finally(() => {
+ state.running--;
+ state.pendingChecks--;
+ tickVerification();
+ finalizeIfDone();
+ pumpQueue();
+ });
+ }
+}
+
+async function verifyLink(url, signal) {
+ if (!url) return null;
+ try {
+ const res = await fetch("/api/link-check", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url }),
+ signal
+ });
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+/* ----------------------------- CARDS --------------------------------------*/
+function makeCard({ url }) {
+ if (!url) return null;
+ const host = parseHost(url);
+ const { icon, brand, label } = resolvePlatform(host);
+
+ const card = document.createElement("article");
+ card.className = "profile-card fade-in";
+ card.dataset.url = url;
+
+ const iconHTML = ` `;
+ card.innerHTML = `
+
+
+ `;
+ return card;
+}
+
+function updateCard(url, res) {
+ const card = cardsContainer.querySelector(`article[data-url="${cssEscape(url)}"]`);
+ if (!card) return;
+
+ const statusEl = card.querySelector(".verification-status");
+ const btn = card.querySelector(".btn");
+
+ if (!res) {
+ statusEl.className = "verification-status validation-badge unknown";
+ statusEl.textContent = "⚠️ Verifica non riuscita";
+ if (btn) {
+ btn.textContent = "Apri comunque";
+ btn.classList.remove('disabled', 'pointer-events-none', 'opacity-60');
+ btn.href = url;
+ }
+ return;
+ }
+
+ if (res.valid) {
+ statusEl.className = "verification-status validation-badge valid";
+ statusEl.innerHTML = `✅ Pagina verificata${res.reason ? ` (${htmlEscape(res.reason)}) ` : ""}`;
+ if (btn) {
+ btn.textContent = "Visita";
+ btn.classList.remove('disabled', 'pointer-events-none', 'opacity-60');
+ btn.href = url;
+ }
+ state.validCount++;
+ } else {
+ statusEl.className = "verification-status validation-badge invalid";
+ statusEl.innerHTML = `⚠️ Pagina non valida${res.reason ? ` (${htmlEscape(res.reason)}) ` : ""}`;
+ btn?.remove();
+ state.invalidCount++;
+ }
+ updateDashboard();
+}
+
+function setStatus(url, status, reason = '') {
+ const card = cardsContainer.querySelector(`article[data-url="${cssEscape(url)}"]`);
+ if (!card) return;
+ const statusEl = card.querySelector(".verification-status");
+ const btn = card.querySelector(".btn");
+
+ if (status === 'valid') {
+ statusEl.className = "verification-status status-badge valid";
+ statusEl.innerHTML = `✅ Pagina verificata${reason ? ` (${htmlEscape(reason)}) ` : ""}`;
+ if (btn) {
+ btn.textContent = "Visita";
+ btn.classList.remove('disabled', 'pointer-events-none', 'opacity-60');
+ btn.href = card.dataset.url;
+ }
+ } else {
+ statusEl.className = "verification-status status-badge invalid";
+ statusEl.innerHTML = `⚠️ Pagina non valida${reason ? ` (${htmlEscape(reason)}) ` : ""}`;
+ btn?.remove();
+ }
+}
+
+/* ------------------------- ADD & FINALIZE ---------------------------------*/
+function addCards(links) {
+ if (!links?.length) return;
+
+ if (state.pendingChecks === 0 && state.queue.length === 0) {
+ startVerification(links.length);
+ } else if (verifyBox && vpTotal) {
+ vpTotal.textContent = Number(vpTotal.textContent) + links.length;
+ }
+
+ hide(noResultsEl);
+ const frag = document.createDocumentFragment();
+ links.forEach(url => {
+ if (cardsContainer.querySelector(`article[data-url="${cssEscape(url)}"]`)) return;
+ const c = makeCard({ url });
+ if (c) {
+ frag.appendChild(c);
+ state.cardsCount++;
+ enqueueVerification(url);
+ }
+ });
+ cardsContainer.appendChild(frag);
+ updateDashboard();
+}
+
+function finalizeIfDone() {
+ // overlay off solo quando TUTTO è finito
+ const done = state.sherlockFinished && state.pendingChecks === 0 && state.queue.length === 0 && state.running === 0;
+ if (!done) return;
+ if (state.finishedFired) return;
+ state.finishedFired = true;
+
+ showLoading(false);
+ if (state.cardsCount === 0) {
+ show(noResultsEl);
+ }
+}
+
+/* ---------------------------- RESET ---------------------------------------*/
+function fullResetUI() {
+ stopStream();
+ state.abortCtrl?.abort();
+
+ consoleEl && (consoleEl.textContent = "");
+ hide(noResultsEl);
+ cardsContainer && (cardsContainer.innerHTML = "");
+ hide(verifyBox);
+ if (vpDone) vpDone.textContent = "0";
+ if (vpTotal) vpTotal.textContent = "0";
+
+ state.sherlockFinished = false;
+ state.pendingChecks = 0;
+ state.cardsCount = 0;
+ state.noResultTimer = null;
+ state.abortCtrl = null;
+ state.queue = [];
+ state.running = 0;
+ state.validCount = 0;
+ state.invalidCount = 0;
+ state.consoleVisible = false;
+ state.finishedFired = false;
+
+ hide(dashboardEl);
+ hide(consoleContainer);
+ toggleConsoleBtn.textContent = 'Mostra console';
+ toggleDetailsBtn.textContent = 'Mostra dettagli';
+ cardsContainer.classList.add('details-hidden');
+
+ showLoading(false);
+}
+
+/* ---------------------------- EVENTS --------------------------------------*/
+form?.addEventListener("submit", async e => {
+ e.preventDefault();
+ const nome = (form.nome ? form.nome.value : form.query.value).trim();
+ const cognome = (form.cognome ? form.cognome.value : "").trim();
+ if (!nome && !cognome) return;
+
+ fullResetUI();
+ state.abortCtrl = new AbortController();
+
+ appendConsoleLine(`[${new Date().toLocaleTimeString()}] Avvio ricerca per: ${nome} ${cognome}`);
+
+ startStream({ nome, cognome });
+
+ // eventuale fetch /api/search (se vuoi ancora usarlo)
+ const data = await safeFetchJSON(`/api/search?nome=${encodeURIComponent(nome)}&cognome=${encodeURIComponent(cognome)}`, state.abortCtrl.signal);
+ if (data?.links?.length) {
+ addCards(data.links);
+ }
+});
+
+toggleConsoleBtn?.addEventListener('click', () => {
+ state.consoleVisible = !state.consoleVisible;
+ if (state.consoleVisible) {
+ show(consoleContainer);
+ toggleConsoleBtn.textContent = 'Nascondi console';
+ } else {
+ hide(consoleContainer);
+ toggleConsoleBtn.textContent = 'Mostra console';
+ }
+});
+
+window.addEventListener("beforeunload", stopStream);
+window.addEventListener("keydown", e => {
+ if (e.key === "Escape" && state.abortCtrl) {
+ state.abortCtrl.abort();
+ stopStream();
+ showLoading(false);
+ appendConsoleLine(`[${new Date().toLocaleTimeString()}] Ricerca interrotta.`);
+ }
+});
+
+/* -------------------------- SAFE FETCH JSON -------------------------------*/
+async function safeFetchJSON(url, signal) {
+ try {
+ const res = await fetch(url, { signal });
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+/* ------------------------- TOGGLE DETAILS (GLOBAL) -----------------------*/
+document.addEventListener('DOMContentLoaded', () => {
+ const cardsWrapper = document.getElementById('cards') || document.getElementById('cards-container');
+ const toggleDetailsBtn = document.getElementById('toggle-details');
+
+ if (!cardsWrapper || !toggleDetailsBtn) return;
+
+ // Funzione per aggiornare l'etichetta del pulsante
+ const updateToggleBtnLabel = () => {
+ const hidden = cardsWrapper.classList.contains('details-hidden');
+ toggleDetailsBtn.textContent = hidden ? 'Mostra dettagli' : 'Nascondi dettagli';
+ };
+
+ // Toggle globale dei dettagli
+ toggleDetailsBtn.addEventListener('click', () => {
+ cardsWrapper.classList.toggle('details-hidden');
+ updateToggleBtnLabel();
+ });
+
+ // Mostra il pulsante solo se ci sono card
+ const showToggleIfCards = () => {
+ const hasCards = cardsWrapper.children.length > 0;
+ toggleDetailsBtn.classList.toggle('hidden', !hasCards);
+ };
+
+ // Osserva aggiunte/rimozioni di card
+ const observer = new MutationObserver(showToggleIfCards);
+ observer.observe(cardsWrapper, { childList: true });
+
+ // Inizializza UI
+ showToggleIfCards();
+ updateToggleBtnLabel();
+ cardsWrapper.classList.add('details-hidden'); // Dettagli nascosti di default
+});
+
+// Inizializza UI al caricamento
+document.addEventListener('DOMContentLoaded', fullResetUI);
\ No newline at end of file
diff --git a/Social-Finder/backend/templates/disclaimer.html b/Social-Finder/backend/templates/disclaimer.html
new file mode 100644
index 0000000000000000000000000000000000000000..5536f1477269a087a5c91a1edcd5eabce8698ee6
--- /dev/null
+++ b/Social-Finder/backend/templates/disclaimer.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+ Disclaimer — Progetto Studentesco
+
+
+
+
+
+ 🎓 Progetto studentesco
+
+
+
+
+ Disclaimer
+
+ Progetto studentesco dimostrativo , creato a scopo didattico e senza fini commerciali. I contenuti sono forniti "così come sono" senza garanzie.
+
+
+ Marchi
+ I marchi citati appartengono ai rispettivi proprietari. Non esiste alcuna affiliazione o approvazione.
+
+ Uso
+ È vietato il riutilizzo dei contenuti per scopi commerciali. L’uso è limitato a consultazione e studio.
+
+ Contatti
+
+ Per segnalazioni scrivi a pastimattia772@gmail.com .
+
+
+
+
+
+
+
+
diff --git a/Social-Finder/backend/templates/index.html b/Social-Finder/backend/templates/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..fd72c3cba0bec853c9b8dc65273bb546951c7525
--- /dev/null
+++ b/Social-Finder/backend/templates/index.html
@@ -0,0 +1,186 @@
+
+
+
+
+
+ Social Finder –
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Ricerca informazioni sui social media in tempo reale
+
+
+
+
+
+
+
+
+
+
+
+ Totale: 0
+ Valide: 0
+ Non valide: 0
+ In corso: 0
+
+
+ Mostra console
+ Mostra dettagli
+
+
+
+
+
+
+
+
+
+ Console Live ▼ Streaming
+
+
+
+
+
+
+
+
+
+
+
+
+
Elaborazione in corso…
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Progetto studentesco — solo dimostrazione
+
+ Questo sito è un prototipo a scopo didattico , senza fini commerciali. È fornito “così com’è”, senza garanzie; i marchi citati appartengono ai rispettivi proprietari e non esiste alcuna affiliazione . I contenuti potrebbero essere incompleti o imprecisi. Se qualcosa ti riguarda e vuoi la rimozione, contattami.
+
+
+
+
+
OK
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Social-Finder/backend/templates/privacy.html b/Social-Finder/backend/templates/privacy.html
new file mode 100644
index 0000000000000000000000000000000000000000..6b52f645db83bdddbf1f6561fa41d34d2029122b
--- /dev/null
+++ b/Social-Finder/backend/templates/privacy.html
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+ Informativa Privacy — Progetto Studentesco
+
+
+
+
+
+ 🔒 Privacy & GDPR
+
+
+
+
+ Informativa Privacy
+
+ Titolare: Mattia Pasti — pastimattia772@gmail.com
+
+
+ Dati trattati
+
+ Dati tecnici di navigazione (IP, log errori) solo per sicurezza e diagnostica.
+ Cookie tecnici/localStorage (es. preferenze banner). Nessun cookie di profilazione.
+ Dati di contatto (solo se ci scrivi).
+
+
+ Finalità
+ Dimostrazione didattica / portfolio, sicurezza tecnica, gestione contatti volontari.
+
+ Diritti
+
+ Puoi chiedere accesso, rettifica o cancellazione dei tuoi dati. Per farlo scrivi a questa email .
+
+
+
+
+
+
+
+
diff --git a/Social-Finder/docker-compose.yml b/Social-Finder/docker-compose.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5c72de8998cb06913bf7ed7ddc956cacc01463d1
--- /dev/null
+++ b/Social-Finder/docker-compose.yml
@@ -0,0 +1,10 @@
+version: "3.9"
+
+services:
+ web:
+ build: .
+ container_name: socialfinder-flask
+ ports:
+ - "3000:3000"
+ volumes:
+ - ./backend:/app # hot-reload del codice host→container
diff --git a/dashboard.py b/dashboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe61d49deca8408315cd86a25a585afd0c9e3bfd
--- /dev/null
+++ b/dashboard.py
@@ -0,0 +1,36 @@
+import streamlit as st
+
+st.set_page_config(
+ page_title="Ba7ath OSINT Suite",
+ page_icon="🕵️♂️",
+ layout="wide"
+)
+
+st.title("🕵️♂️ Ba7ath OSINT Suite")
+st.markdown("""
+Bienvenue dans votre **laboratoire OSINT d'investigation multi-plateformes**.
+
+Ce dashboard vous permet :
+- D’identifier la présence d’un username sur plus de **474 plateformes** en un clic (Ba7ath Username Search)
+- D’analyser automatiquement l’occupation d’un pseudo/email sur les principaux réseaux (Multi-comptes OSINT)
+- D’enrichir vos recherches par des modules professionnels (leaks, images, cartographie, ...)
+
+**Navigation :**
+Utilisez le menu latéral à gauche pour changer d'outil.
+
+---
+
+> Ce kit est optimisé pour journalistes, enquêteurs, analystes et équipes de veille stratégique.
+> Toutes les analyses s’effectuent localement, les données ne sont pas partagées avec des tiers.
+""")
+
+# Affichage du logo à taille raisonnable
+st.image("logo.png", caption="Ba7ath OSINT, l’investigation en mode turbo", width=200)
+
+st.markdown("""
+---
+### Astuce rapide :
+- **Changez de module à tout moment via le menu**
+- **Sauvegardez vos résultats en CSV pour reporting**
+- **Contactez votre expert OSINT Ba7ath pour tout ajout de fonctionnalité personnalisée**
+""")
diff --git a/downloads/.gitkeep b/downloads/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/favicon.ico b/favicon.ico
new file mode 100644
index 0000000000000000000000000000000000000000..2f602e8efe9905243e7fa00fffeed599279634ee
Binary files /dev/null and b/favicon.ico differ
diff --git a/fb_cookies.json b/fb_cookies.json
new file mode 100644
index 0000000000000000000000000000000000000000..2cd93e067a9ea48450b16a1aef0d37200694b896
--- /dev/null
+++ b/fb_cookies.json
@@ -0,0 +1 @@
+[{"name": "dbln", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "ps_l", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "ps_n", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "ar_debug", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "presence", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "c_user", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "fr", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "xs", "value": "", "domain": ".facebook.com", "path": "/", "expires": -1, "httpOnly": false, "secure": false, "sameSite": "Lax"}, {"name": "datr", "value": "t_ccaertQ3uQdEZuaqKUGSc4", "domain": ".facebook.com", "path": "/", "expires": 1798066106.226236, "httpOnly": true, "secure": true, "sameSite": "None"}, {"name": "sb", "value": "t_ccabEz-kYEWnCAwIBbrEZi", "domain": ".facebook.com", "path": "/", "expires": 1798066106.226411, "httpOnly": true, "secure": true, "sameSite": "None"}, {"name": "wd", "value": "1280x720", "domain": ".facebook.com", "path": "/", "expires": 1764110908, "httpOnly": false, "secure": true, "sameSite": "Lax"}, {"name": "dpr", "value": "1.0000000149011612", "domain": ".facebook.com", "path": "/", "expires": 1764110908, "httpOnly": false, "secure": true, "sameSite": "None"}]
\ No newline at end of file
diff --git a/maigret_reports/.gitkeep b/maigret_reports/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/output.json b/output.json
new file mode 100644
index 0000000000000000000000000000000000000000..aec1ac5cfd3309803e229cfc90c516b9f9113b7c
--- /dev/null
+++ b/output.json
@@ -0,0 +1,5 @@
+[
+{"title": "Le Monde | Paris ", "description": "Le Monde, Paris. 5,795,118 likes \u00b7 336,172 talking about this \u00b7 61,768 were here. L'actualit\u00e9 de r\u00e9f\u00e9rence, par la r\u00e9daction du Monde.", "posts": []}
+][
+{"title": "Pr\u00e9sidence Tunisie \u0631\u0626\u0627\u0633\u0629 \u0627\u0644\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062a\u0648\u0646\u0633\u064a\u0629", "description": "\u200ePr\u00e9sidence Tunisie \u0631\u0626\u0627\u0633\u0629 \u0627\u0644\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062a\u0648\u0646\u0633\u064a\u0629\u200e. 2,698,878 likes \u00b7 41,296 talking about this. \u200e\u0627\u0644\u0635\u0641\u062d\u0629 \u0627\u0644\u0631\u0633\u0645\u064a\u0629 \u0644\u0631\u0626\u0627\u0633\u0629 \u0627\u0644\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062a\u0648\u0646\u0633\u064a\u0629\u200e", "posts": []}
+]
\ No newline at end of file
diff --git a/output.txt b/output.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3cc80e97e321acb9ac14f376d16d8edb5b7bbee7
Binary files /dev/null and b/output.txt differ
diff --git a/pages/10_WaybackURLs.py b/pages/10_WaybackURLs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ffe42c6f840d3be343015ac0bf991ac21288eea
--- /dev/null
+++ b/pages/10_WaybackURLs.py
@@ -0,0 +1,551 @@
+"""
+Page Streamlit : Wayback Machine - URLs historiques
+Module OSINT pour Ba7ath Dashboard
+Avec filtres dynamiques d'affichage
+"""
+
+import streamlit as st
+import sys
+import os
+import pandas as pd
+import time
+import urllib.parse
+
+try:
+ from spectre_modules.wayback_urls import (
+ discover_wayback_urls,
+ download_archived_file,
+ extract_text_from_archived_page
+ )
+except ImportError as e:
+ st.error(f"❌ Erreur d'import du module wayback_urls : {e}")
+ st.stop()
+
+# Configuration de la page
+st.set_page_config(page_title="Wayback URLs", page_icon="🕰️", layout="wide")
+
+# En-tête
+st.title("🕰️ Wayback Machine - URLs Historiques")
+st.caption("Découverte d'URLs, fichiers et pages archivés - Archive.org")
+
+# Avertissement légal
+with st.expander("⚖️ Mentions légales et informations", expanded=False):
+ st.info("""
+ **Wayback Machine - Internet Archive**
+
+ 📚 **Source des données** :
+ - [Internet Archive](https://web.archive.org/) - Organisation à but non lucratif
+ - Plus de 735 milliards de pages web archivées depuis 1996
+ - Accès public et gratuit via CDX API
+
+ 🔍 **Cas d'usage OSINT** :
+ - Découvrir des sous-domaines historiques
+ - Trouver des fichiers sensibles supprimés (.sql, .env, .zip)
+ - Analyser l'évolution d'un site web
+ - Récupérer des documents publics disparus
+
+ ⚠️ **Utilisation éthique** :
+ - Données publiques archivées légalement
+ - Respectez les robots.txt et directives légales
+ - Usage OSINT/recherche uniquement
+ """)
+
+# Formulaire de saisie
+st.markdown("---")
+
+# Ligne 1 : Domaine et options de base
+col1, col2 = st.columns([2, 1])
+
+with col1:
+ domain_input = st.text_input(
+ "🎯 Domaine cible",
+ placeholder="exemple.com (sans http:// ni www)",
+ help="Entrez le nom de domaine à analyser"
+ )
+
+with col2:
+ limit_per_page = st.selectbox(
+ "📊 Limite par page",
+ options=[1000, 5000, 10000],
+ index=2,
+ help="Nombre max d'URLs par requête (10000 = max API)"
+ )
+
+# Ligne 2 : Filtres API (affectent la requête)
+st.write("**Filtres API (limitent les données récupérées)** :")
+col3, col4 = st.columns(2)
+
+with col3:
+ filter_status_enabled = st.checkbox("Filtrer par code HTTP", value=True)
+ if filter_status_enabled:
+ status_codes = st.multiselect(
+ "Codes HTTP à inclure",
+ options=[200, 301, 302, 400, 403, 404, 500],
+ default=[200],
+ help="Seuls ces codes seront récupérés de l'API"
+ )
+ else:
+ status_codes = None
+
+with col4:
+ filter_mime_enabled = st.checkbox("Filtrer par MIME type (API)", value=False)
+ if filter_mime_enabled:
+ mime_types = st.multiselect(
+ "MIME types à inclure",
+ options=[
+ "text/html",
+ "application/pdf",
+ "application/zip",
+ "application/json",
+ "application/xml",
+ "text/plain"
+ ],
+ help="Seuls ces types seront récupérés de l'API"
+ )
+ else:
+ mime_types = None
+
+# Ligne 3 : Options avancées
+st.write("**Options de téléchargement** :")
+col5, col6 = st.columns(2)
+
+with col5:
+ auto_download = st.checkbox(
+ "📥 Télécharger automatiquement les fichiers intéressants",
+ value=False,
+ help="Télécharge les .pdf, .zip, .sql, .env, etc."
+ )
+
+with col6:
+ if auto_download:
+ max_downloads = st.number_input(
+ "Nombre max de fichiers",
+ min_value=1,
+ max_value=100,
+ value=20,
+ help="Limite pour éviter les téléchargements excessifs"
+ )
+ else:
+ max_downloads = 0
+
+# Nettoyage de l'input
+if domain_input:
+ domain_input = domain_input.strip().lower()
+ domain_input = domain_input.replace('http://', '').replace('https://', '')
+ domain_input = domain_input.replace('www.', '')
+ domain_input = domain_input.split('/')[0]
+
+# Bouton de lancement
+discover_btn = st.button("🚀 Lancer la découverte", type="primary", use_container_width=True)
+
+# Exécution de la découverte
+if discover_btn:
+ if not domain_input:
+ st.error("⚠️ Veuillez entrer un nom de domaine")
+ elif '.' not in domain_input or ' ' in domain_input:
+ st.error("⚠️ Format de domaine invalide")
+ else:
+ st.markdown("---")
+
+ # Barre de progression
+ progress_bar = st.progress(0, text="Initialisation...")
+
+ try:
+ # Lancement de la découverte
+ progress_bar.progress(10, text="🕰️ Interrogation de Wayback Machine...")
+
+ with st.spinner("Découverte en cours... Cela peut prendre 1-3 minutes."):
+ results = discover_wayback_urls(
+ domain=domain_input,
+ filter_status=status_codes if filter_status_enabled else None,
+ filter_mimetype=mime_types if filter_mime_enabled else None,
+ limit=limit_per_page,
+ auto_download=auto_download,
+ max_downloads=max_downloads if auto_download else 0
+ )
+
+ progress_bar.progress(100, text="✅ Découverte terminée !")
+ progress_bar.empty()
+
+ # Sauvegarder les résultats dans la session
+ st.session_state['wayback_results'] = results
+
+ except Exception as e:
+ progress_bar.empty()
+ st.error(f"❌ Erreur lors de la découverte : {str(e)}")
+
+ with st.expander("🐛 Détails de l'erreur (pour debug)"):
+ st.exception(e)
+
+# Affichage des résultats (persiste après le clic)
+if 'wayback_results' in st.session_state:
+ results = st.session_state['wayback_results']
+
+ if results['urls']:
+ st.success(f"✅ **{len(results['urls'])} URLs** découvertes pour **{results['domain']}**")
+
+ # ========================================
+ # FILTRES D'AFFICHAGE DYNAMIQUES
+ # ========================================
+ st.markdown("---")
+ st.subheader("🔍 Filtres d'affichage (n'affectent pas les données)")
+
+ col_filter1, col_filter2, col_filter3 = st.columns(3)
+
+ with col_filter1:
+ # Filtre par extension
+ all_extensions = sorted(set(u['extension'] for u in results['urls'] if u['extension']))
+ selected_extensions = st.multiselect(
+ "📁 Filtrer par extension",
+ options=['Toutes'] + all_extensions,
+ default=['Toutes'],
+ help="Affiche uniquement ces extensions"
+ )
+
+ with col_filter2:
+ # Filtre textuel sur URL
+ text_filter = st.text_input(
+ "🔎 Recherche textuelle",
+ placeholder="Rechercher dans les URLs...",
+ help="Filtre les URLs contenant ce texte"
+ )
+
+ with col_filter3:
+ # Filtre par hostname
+ all_hostnames = sorted(set(u['hostname'] for u in results['urls']))
+ selected_hostnames = st.multiselect(
+ "🏠 Filtrer par hostname",
+ options=['Tous'] + all_hostnames,
+ default=['Tous'],
+ help="Affiche uniquement ces hostnames"
+ )
+
+ # Appliquer les filtres
+ filtered_urls = results['urls']
+
+ # Filtre extension
+ if 'Toutes' not in selected_extensions and selected_extensions:
+ filtered_urls = [u for u in filtered_urls if u['extension'] in selected_extensions]
+
+ # Filtre textuel
+ if text_filter:
+ filtered_urls = [u for u in filtered_urls if text_filter.lower() in urllib.parse.unquote(u['url']).lower()]
+
+ # Filtre hostname
+ if 'Tous' not in selected_hostnames and selected_hostnames:
+ filtered_urls = [u for u in filtered_urls if u['hostname'] in selected_hostnames]
+
+ # Statistiques filtrées
+ st.info(f"**Affichage : {len(filtered_urls)} / {len(results['urls'])} URLs** (après filtrage)")
+
+ # ========================================
+ # FIN FILTRES
+ # ========================================
+
+ # Statistiques principales
+ stats = results.get('stats', {})
+
+ col_stat1, col_stat2, col_stat3, col_stat4 = st.columns(4)
+ with col_stat1:
+ st.metric("🌐 URLs totales", len(results['urls']))
+ with col_stat2:
+ st.metric("🏠 Sous-domaines", stats.get('unique_hostnames', 0))
+ with col_stat3:
+ st.metric("📁 Fichiers intéressants", len(stats.get('interesting_files', [])))
+ with col_stat4:
+ st.metric("📄 Pages HTML", len(stats.get('html_pages', [])))
+
+ # Affichage des téléchargements
+ if results.get('downloaded_files'):
+ st.success(f"✅ {len(results['downloaded_files'])} fichiers téléchargés dans `/downloads`")
+
+ # Organisation en onglets
+ tab1, tab2, tab3, tab4, tab5 = st.tabs([
+ "📋 Toutes les URLs",
+ "📁 Fichiers intéressants",
+ "📄 Pages HTML",
+ "📊 Statistiques",
+ "📥 Export"
+ ])
+
+ # --- ONGLET : TOUTES LES URLs ---
+ with tab1:
+ st.subheader(f"Liste des URLs ({len(filtered_urls)} affichées)")
+
+ # DataFrame avec URLs filtrées
+ df_filtered = pd.DataFrame(filtered_urls)
+
+ if not df_filtered.empty:
+ # Sélection des colonnes à afficher
+ display_cols = ['hostname', 'date_archived', 'status_code',
+ 'mime_type', 'extension', 'wayback_url']
+
+ st.dataframe(
+ df_filtered[display_cols],
+ width='stretch',
+ hide_index=True,
+ column_config={
+ 'hostname': st.column_config.TextColumn('Hostname', width='medium'),
+ 'date_archived': st.column_config.TextColumn('Date archivée', width='medium'),
+ 'status_code': st.column_config.NumberColumn('HTTP', format="%d", width='small'),
+ 'mime_type': st.column_config.TextColumn('MIME type', width='medium'),
+ 'extension': st.column_config.TextColumn('Ext', width='small'),
+ 'wayback_url': st.column_config.LinkColumn('🔗 Ouvrir', width='small')
+ }
+ )
+
+ # Section URLs originales copiables
+ with st.expander("📋 URLs originales (copiables)"):
+ original_urls = '\n'.join([u['url'] for u in filtered_urls[:100]])
+ st.code(original_urls)
+
+ # Liens Wayback directs
+ with st.expander("🔗 Liens Wayback Machine (10 premiers filtrés)"):
+ for url_data in filtered_urls[:10]:
+ st.markdown(f"🌐 **[{url_data['wayback_url']}]({url_data['wayback_url']})**")
+ st.caption(f" ↳ Original : `{url_data['url']}`")
+ st.markdown("---")
+ else:
+ st.warning("Aucune URL ne correspond aux filtres sélectionnés")
+
+ # --- ONGLET : FICHIERS INTÉRESSANTS ---
+ with tab2:
+ st.subheader("📁 Fichiers sensibles découverts")
+
+ interesting = stats.get('interesting_files', [])
+
+ # Appliquer les filtres aux fichiers intéressants
+ filtered_interesting = interesting
+ if 'Toutes' not in selected_extensions and selected_extensions:
+ filtered_interesting = [f for f in filtered_interesting if f['extension'] in selected_extensions]
+ if text_filter:
+ filtered_interesting = [f for f in filtered_interesting if text_filter.lower() in urllib.parse.unquote(f['url']).lower()]
+
+ if filtered_interesting:
+ st.write(f"**{len(filtered_interesting)} / {len(interesting)} fichiers** affichés (après filtrage) :")
+
+ df_interesting = pd.DataFrame(filtered_interesting)
+
+ # Affichage avec lien Wayback
+ st.dataframe(
+ df_interesting[['extension', 'date_archived', 'wayback_url']],
+ width='stretch',
+ hide_index=True,
+ column_config={
+ 'extension': st.column_config.TextColumn('Type', width='small'),
+ 'date_archived': st.column_config.TextColumn('Date archivée', width='medium'),
+ 'wayback_url': st.column_config.LinkColumn('🔗 Ouvrir dans Wayback', width='large')
+ }
+ )
+
+ # URLs originales en expander
+ with st.expander("📋 URLs originales des fichiers"):
+ for f in filtered_interesting[:20]:
+ st.code(f['url'])
+
+ # Actions de téléchargement
+ st.write("**Actions disponibles :**")
+
+ selected_file = st.selectbox(
+ "Sélectionner un fichier à télécharger",
+ options=range(len(filtered_interesting)),
+ format_func=lambda i: f"{filtered_interesting[i]['extension']} - {filtered_interesting[i]['url'][:60]}..."
+ )
+
+ col_dl1, col_dl2 = st.columns(2)
+
+ with col_dl1:
+ if st.button("📥 Télécharger ce fichier", use_container_width=True):
+ file_data = filtered_interesting[selected_file]
+
+ with st.spinner(f"Téléchargement de {file_data['extension']}..."):
+ success, path = download_archived_file(
+ file_data['url'],
+ file_data['timestamp']
+ )
+
+ if success:
+ st.success(f"✅ Fichier sauvegardé : `{path}`")
+ else:
+ st.error("❌ Échec du téléchargement")
+
+ with col_dl2:
+ st.link_button(
+ "🔗 Ouvrir dans Wayback",
+ filtered_interesting[selected_file]['wayback_url'],
+ use_container_width=True
+ )
+ else:
+ if interesting:
+ st.info(f"{len(interesting)} fichiers trouvés mais aucun ne correspond aux filtres")
+ else:
+ st.info("Aucun fichier intéressant trouvé avec les filtres API actuels")
+
+ # --- ONGLET : PAGES HTML ---
+ with tab3:
+ st.subheader("📄 Pages HTML analysables")
+
+ html_pages = stats.get('html_pages', [])
+
+ # Appliquer les filtres textuels
+ filtered_html = html_pages
+ if text_filter:
+ filtered_html = [p for p in filtered_html if text_filter.lower() in urllib.parse.unquote(p['url']).lower()]
+
+ if filtered_html:
+ st.write(f"**{len(filtered_html)} / {len(html_pages)} pages HTML** affichées (après filtrage) :")
+
+ # Sélection d'une page
+ selected_page = st.selectbox(
+ "Sélectionner une page",
+ options=range(min(50, len(filtered_html))),
+ format_func=lambda i: f"{filtered_html[i]['date_archived']} - {filtered_html[i]['url'][:60]}..."
+ )
+
+ page_data = filtered_html[selected_page]
+
+ col_page1, col_page2 = st.columns(2)
+
+ with col_page1:
+ if st.button("📝 Extraire le texte", use_container_width=True):
+ with st.spinner("Extraction du texte en cours..."):
+ text = extract_text_from_archived_page(
+ page_data['url'],
+ page_data['timestamp']
+ )
+
+ if text:
+ st.success("✅ Texte extrait avec succès")
+ st.text_area(
+ "Contenu textuel",
+ value=text,
+ height=400
+ )
+
+ # Bouton de téléchargement du texte
+ st.download_button(
+ label="💾 Télécharger le texte",
+ data=text.encode('utf-8'),
+ file_name=f"text_{results['domain']}_{page_data['timestamp']}.txt",
+ mime="text/plain"
+ )
+ else:
+ st.error("❌ Impossible d'extraire le texte")
+
+ with col_page2:
+ st.link_button(
+ "🔗 Ouvrir dans Wayback",
+ page_data['wayback_url'],
+ use_container_width=True
+ )
+ else:
+ if html_pages:
+ st.info(f"{len(html_pages)} pages trouvées mais aucune ne correspond aux filtres")
+ else:
+ st.info("Aucune page HTML trouvée (utilisez le filtre MIME type API)")
+
+ # --- ONGLET : STATISTIQUES ---
+ with tab4:
+ st.subheader("📊 Statistiques détaillées (données complètes)")
+
+ # Codes HTTP
+ st.write("**Répartition par code HTTP :**")
+ status_codes_stats = stats.get('status_codes', {})
+ for code, count in sorted(status_codes_stats.items(), key=lambda x: -x[1]):
+ st.write(f"- **{code}** : {count} URLs")
+
+ st.markdown("---")
+
+ # MIME types
+ st.write("**Répartition par MIME type (top 10) :**")
+ mime_stats = stats.get('mime_types', {})
+ for mime, count in sorted(mime_stats.items(), key=lambda x: -x[1])[:10]:
+ st.write(f"- **{mime}** : {count} URLs")
+
+ st.markdown("---")
+
+ # Extensions
+ st.write("**Top extensions de fichiers :**")
+ ext_stats = stats.get('file_extensions', {})
+ for ext, count in sorted(ext_stats.items(), key=lambda x: -x[1])[:15]:
+ st.write(f"- **{ext}** : {count} fichiers")
+
+ # --- ONGLET : EXPORT ---
+ with tab5:
+ st.subheader("📥 Exportation des données")
+
+ # Export des données filtrées ou complètes
+ export_choice = st.radio(
+ "Que voulez-vous exporter ?",
+ options=["Données filtrées actuelles", "Toutes les données"],
+ index=0
+ )
+
+ if export_choice == "Données filtrées actuelles":
+ export_df = pd.DataFrame(filtered_urls)
+ export_label = f"filtré ({len(filtered_urls)} URLs)"
+ else:
+ export_df = pd.DataFrame(results['urls'])
+ export_label = f"complet ({len(results['urls'])} URLs)"
+
+ col_exp1, col_exp2 = st.columns(2)
+
+ with col_exp1:
+ st.download_button(
+ label=f"📥 Télécharger {export_label} (CSV)",
+ data=export_df.to_csv(index=False, encoding='utf-8-sig').encode('utf-8-sig'),
+ file_name=f"wayback_urls_{results['domain'].replace('.', '_')}_{export_choice.replace(' ', '_')}.csv",
+ mime="text/csv",
+ use_container_width=True
+ )
+
+ with col_exp2:
+ # Rapport automatique
+ if results.get('report_filename'):
+ report_path = os.path.join('reports', results['report_filename'])
+ if os.path.exists(report_path):
+ with open(report_path, 'rb') as f:
+ report_content = f.read()
+
+ st.download_button(
+ label="📄 Télécharger le rapport auto-généré",
+ data=report_content,
+ file_name=results['report_filename'],
+ mime="text/csv",
+ use_container_width=True
+ )
+
+ # Export des fichiers intéressants uniquement
+ if stats.get('interesting_files'):
+ interesting_df = pd.DataFrame(stats['interesting_files'])
+ st.download_button(
+ label="📁 Télécharger uniquement les fichiers intéressants (CSV)",
+ data=interesting_df.to_csv(index=False, encoding='utf-8-sig').encode('utf-8-sig'),
+ file_name=f"interesting_files_{results['domain'].replace('.', '_')}.csv",
+ mime="text/csv",
+ use_container_width=True
+ )
+
+ # Aperçu
+ with st.expander("👁️ Aperçu des données exportables"):
+ st.dataframe(export_df, width='stretch')
+
+ st.caption(f"""
+ 📊 **Format du rapport**
+ - Colonnes : url, hostname, date_archived, status_code, mime_type, extension, wayback_url, timestamp
+ - Total d'entrées : {len(export_df)}
+ - Encodage : UTF-8 BOM (compatible Excel)
+ """)
+
+ else:
+ st.warning("⚠️ Aucune URL trouvée pour ce domaine")
+ st.info("""
+ **Raisons possibles** :
+ - Le domaine n'a jamais été archivé par Wayback Machine
+ - Les filtres API sont trop restrictifs
+ - Le domaine est trop récent
+ """)
+
+# Pied de page
+st.markdown("---")
+st.caption("🕵️ Ba7ath OSINT Suite | Module Wayback Machine - Internet Archive")
diff --git a/pages/11_Email_extractor.py b/pages/11_Email_extractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..b53655e7ce50b9937e328abae73e47459298a542
--- /dev/null
+++ b/pages/11_Email_extractor.py
@@ -0,0 +1,357 @@
+"""
+Page Streamlit : Email Harvester
+Module OSINT pour Ba7ath Dashboard
+Extraction passive d'emails depuis pages web publiques
+"""
+
+import streamlit as st
+import sys
+import os
+import pandas as pd
+import time
+
+# Ajouter le chemin des modules
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'spectre_modules'))
+
+try:
+ from email_harvester import harvest_emails
+except ImportError as e:
+ st.error(f"❌ Erreur d'import du module email_harvester : {e}")
+ st.stop()
+
+st.set_page_config(page_title="Email extractor", page_icon="📧", layout="wide")
+
+st.title("📧 Email extractor")
+st.caption("Extraction passive d'emails depuis pages web publiques")
+
+with st.expander("⚖️ Mentions légales et éthique", expanded=False):
+ st.warning("""
+ **Utilisation responsable uniquement**
+
+ ⚠️ **Règles d'utilisation** :
+ - Respecte automatiquement les fichiers `robots.txt` (option désactivable ci-dessous)
+ - N'utilisez que sur des sites publics
+ - Pas de spam ni de harcèlement
+ - Respectez le RGPD et les lois locales
+
+ 📚 **Sources de données** :
+ - Pages web publiques accessibles
+ - Validation DNS automatique (MX records)
+ - Emails extraits via regex + parsing HTML
+
+ 🚫 **Interdit** :
+ - Utilisation commerciale sans consentement
+ - Spam ou phishing
+ - Violation de la vie privée
+
+ ✅ **Cas d'usage légitimes** :
+ - Recherche de contacts professionnels publics
+ - Investigation OSINT avec autorisation
+ - Audit de sécurité (bug bounty)
+ """)
+
+st.markdown("---")
+
+# Mode de saisie
+input_mode = st.radio(
+ "Mode de saisie",
+ options=["URL unique", "Batch (plusieurs URLs)"],
+ horizontal=True
+)
+
+if input_mode == "URL unique":
+ url_input = st.text_input(
+ "🌐 URL cible",
+ placeholder="https://exemple.com ou exemple.com",
+ help="Entrez l'URL de la page à analyser"
+ )
+ urls_list = [url_input] if url_input else []
+else:
+ urls_text = st.text_area(
+ "📋 Liste d'URLs (une par ligne)",
+ placeholder="https://exemple1.com\nexemple2.com\nhttps://exemple3.com/contact",
+ height=150,
+ help="Collez une URL par ligne"
+ )
+ urls_list = [url.strip() for url in urls_text.split('\n') if url.strip()]
+
+st.write("**Options d'extraction** :")
+col1, col2 = st.columns(2)
+with col1:
+ validate_dns = st.checkbox(
+ "🔍 Valider les emails (DNS MX)",
+ value=True,
+ help="Vérifie que le domaine de l'email a des MX records"
+ )
+with col2:
+ follow_links = st.checkbox(
+ "🔗 Suivre les liens internes",
+ value=False,
+ help="⚠️ Augmente considérablement le temps de scan"
+ )
+
+col3, _ = st.columns([1, 1])
+with col3:
+ respect_robots = st.checkbox(
+ "🤖 Respecter robots.txt",
+ value=True,
+ help="Si décoché, l'outil passe outre les restrictions du site (déconseillé sans autorisation explicite)"
+ )
+
+if urls_list:
+ st.info(f"📊 **{len(urls_list)} URL(s)** prêtes à être analysées")
+
+harvest_btn = st.button("🚀 Lancer l'extraction", type="primary", use_container_width=True)
+
+if harvest_btn:
+ if not urls_list:
+ st.error("⚠️ Veuillez entrer au moins une URL")
+ else:
+ st.markdown("---")
+ progress_bar = st.progress(0, text="Initialisation...")
+
+ try:
+ estimated_time = len(urls_list) * 3 # ~3s par URL
+ progress_bar.progress(10, text=f"⏱️ Temps estimé : {estimated_time}s")
+ with st.spinner(f"Extraction en cours sur {len(urls_list)} URL(s)..."):
+ results = harvest_emails(
+ urls=urls_list,
+ validate_dns=validate_dns,
+ follow_links=follow_links,
+ export_csv=True,
+ respect_robots_txt=respect_robots
+ )
+ progress_bar.progress(100, text="✅ Extraction terminée !")
+ progress_bar.empty()
+ st.session_state['email_results'] = results
+
+ except Exception as e:
+ progress_bar.empty()
+ st.error(f"❌ Erreur lors de l'extraction : {str(e)}")
+
+ with st.expander("🐛 Détails de l'erreur (pour debug)"):
+ st.exception(e)
+
+# Affichage des résultats
+if 'email_results' in st.session_state:
+ results = st.session_state['email_results']
+
+ if results['total_found'] > 0:
+ st.success(f"✅ **{results['total_found']} emails uniques** trouvés sur {len(results['urls_scanned'])} URLs")
+
+ col_stat1, col_stat2, col_stat3, col_stat4 = st.columns(4)
+ with col_stat1:
+ st.metric("📧 Emails uniques", results['total_found'])
+ with col_stat2:
+ st.metric("🌐 URLs scannées", len(results['urls_scanned']))
+ with col_stat3:
+ st.metric("✅ Succès", results['successful_scans'])
+ with col_stat4:
+ st.metric("❌ Échecs", results['failed_scans'])
+
+ tab1, tab2, tab3, tab4 = st.tabs([
+ "📧 Liste des emails",
+ "🌐 URLs scannées",
+ "📊 Statistiques",
+ "📥 Export"
+ ])
+
+ with tab1:
+ st.subheader("📧 Emails extraits")
+ col_filter1, col_filter2 = st.columns(2)
+ with col_filter1:
+ all_domains = sorted(set(email['email'].split('@')[1] for email in results['all_emails']))
+ selected_domains = st.multiselect(
+ "Filtrer par domaine",
+ options=['Tous'] + all_domains,
+ default=['Tous']
+ )
+ with col_filter2:
+ dns_filter = st.selectbox(
+ "Validation DNS",
+ options=['Tous', 'Valides uniquement', 'Invalides uniquement', 'Non vérifiés']
+ )
+
+ filtered_emails = results['all_emails']
+ if 'Tous' not in selected_domains and selected_domains:
+ filtered_emails = [e for e in filtered_emails if e['email'].split('@')[1] in selected_domains]
+ if dns_filter == 'Valides uniquement':
+ filtered_emails = [e for e in filtered_emails if e.get('dns_valid') == True]
+ elif dns_filter == 'Invalides uniquement':
+ filtered_emails = [e for e in filtered_emails if e.get('dns_valid') == False]
+ elif dns_filter == 'Non vérifiés':
+ filtered_emails = [e for e in filtered_emails if e.get('dns_valid') is None]
+
+ st.info(f"**{len(filtered_emails)} / {len(results['all_emails'])} emails** affichés (après filtrage)")
+
+ if filtered_emails:
+ df_emails = pd.DataFrame(filtered_emails)
+ display_cols = ['email', 'source_url']
+ if 'dns_valid' in df_emails.columns:
+ display_cols.append('dns_valid')
+ st.dataframe(
+ df_emails[display_cols],
+ width='stretch',
+ hide_index=True,
+ column_config={
+ 'email': st.column_config.TextColumn('Email', width='large'),
+ 'source_url': st.column_config.LinkColumn('Source URL', width='large'),
+ 'dns_valid': st.column_config.CheckboxColumn('DNS Valide', width='small')
+ }
+ )
+ with st.expander("📋 Liste d'emails (copiable)"):
+ emails_text = '\n'.join([f"{e['email']} ({e['source_url']})" for e in filtered_emails])
+ st.code(emails_text)
+ else:
+ st.warning("Aucun email ne correspond aux filtres sélectionnés")
+
+ with tab2:
+ st.subheader("🌐 URLs analysées")
+ urls_data = []
+ for scan in results['urls_scanned']:
+ urls_data.append({
+ 'URL': scan['url'],
+ 'Titre': scan.get('title', 'N/A')[:50] + '...' if scan.get('title') else 'N/A',
+ 'Emails trouvés': scan.get('total_found', 0),
+ 'Statut': scan['status'],
+ 'Erreur': scan.get('error', '')[:50] if scan.get('error') else ''
+ })
+ df_urls = pd.DataFrame(urls_data)
+ st.dataframe(
+ df_urls,
+ width='stretch',
+ hide_index=True,
+ column_config={
+ 'URL': st.column_config.LinkColumn('URL', width='large'),
+ 'Titre': st.column_config.TextColumn('Titre', width='medium'),
+ 'Emails trouvés': st.column_config.NumberColumn('Emails', format="%d", width='small'),
+ 'Statut': st.column_config.TextColumn('Statut', width='small'),
+ 'Erreur': st.column_config.TextColumn('Erreur', width='medium')
+ }
+ )
+ with st.expander("🔍 Détails par URL"):
+ selected_url = st.selectbox(
+ "Sélectionner une URL",
+ options=[scan['url'] for scan in results['urls_scanned']]
+ )
+ scan_detail = next((s for s in results['urls_scanned'] if s['url'] == selected_url), None)
+ if scan_detail:
+ st.json(scan_detail)
+
+ with tab3:
+ st.subheader("📊 Statistiques détaillées")
+ st.write("**Répartition par domaine d'email :**")
+ domain_counts = {}
+ for email in results['all_emails']:
+ domain = email['email'].split('@')[1]
+ domain_counts[domain] = domain_counts.get(domain, 0) + 1
+ for domain, count in sorted(domain_counts.items(), key=lambda x: -x[1])[:10]:
+ st.write(f"- **{domain}** : {count} emails")
+ st.markdown("---")
+ if validate_dns:
+ st.write("**Validation DNS :**")
+ dns_valid_count = sum(1 for e in results['all_emails'] if e.get('dns_valid') == True)
+ dns_invalid_count = sum(1 for e in results['all_emails'] if e.get('dns_valid') == False)
+ col_dns1, col_dns2 = st.columns(2)
+ with col_dns1:
+ st.metric("✅ DNS Valides", dns_valid_count)
+ with col_dns2:
+ st.metric("❌ DNS Invalides", dns_invalid_count)
+ st.markdown("---")
+ st.write("**Performance du scan :**")
+ st.write(f"- URLs scannées : {len(results['urls_scanned'])}")
+ st.write(f"- Succès : {results['successful_scans']}")
+ st.write(f"- Échecs : {results['failed_scans']}")
+ st.write(f"- Taux de réussite : {(results['successful_scans'] / len(results['urls_scanned']) * 100):.1f}%")
+
+ with tab4:
+ st.subheader("📥 Exportation des données")
+ export_choice = st.radio(
+ "Que voulez-vous exporter ?",
+ options=["Emails uniquement", "Données complètes (avec sources)"],
+ index=1
+ )
+ col_exp1, col_exp2 = st.columns(2)
+ with col_exp1:
+ if export_choice == "Emails uniquement":
+ emails_only = '\n'.join(sorted(results['unique_emails']))
+ st.download_button(
+ label="📧 Télécharger liste d'emails (TXT)",
+ data=emails_only.encode('utf-8'),
+ file_name=f"emails_{time.strftime('%Y%m%d_%H%M%S')}.txt",
+ mime="text/plain",
+ use_container_width=True
+ )
+ else:
+ export_df = pd.DataFrame(results['all_emails'])
+ export_df['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
+ st.download_button(
+ label="📥 Télécharger données complètes (CSV)",
+ data=export_df.to_csv(index=False, encoding='utf-8-sig').encode('utf-8-sig'),
+ file_name=f"emails_complet_{time.strftime('%Y%m%d_%H%M%S')}.csv",
+ mime="text/csv",
+ use_container_width=True
+ )
+ with col_exp2:
+ if results.get('report_filename'):
+ report_path = os.path.join('reports', results['report_filename'])
+ if os.path.exists(report_path):
+ with open(report_path, 'rb') as f:
+ report_content = f.read()
+ st.download_button(
+ label="📄 Télécharger le rapport auto-généré",
+ data=report_content,
+ file_name=results['report_filename'],
+ mime="text/csv",
+ use_container_width=True
+ )
+ with st.expander("👁️ Aperçu des données exportables"):
+ if export_choice == "Emails uniquement":
+ st.code(emails_only)
+ else:
+ st.dataframe(export_df, width='stretch')
+ st.caption(f"""
+ 📊 **Format du rapport**
+ - Total d'emails : {len(results['all_emails'])}
+ - Emails uniques : {results['total_found']}
+ - Encodage : UTF-8 {'BOM ' if export_choice != 'Emails uniquement' else ''}
+ """)
+
+ else:
+ st.warning("⚠️ Aucun email trouvé")
+ if results['failed_scans'] > 0:
+ st.error(f"❌ {results['failed_scans']} URL(s) ont échoué")
+ with st.expander("🔍 Détails des échecs"):
+ for scan in results['urls_scanned']:
+ if scan['status'] != 'success':
+ st.write(f"**{scan['url']}** : {scan.get('error', 'Erreur inconnue')}")
+
+st.markdown("---")
+st.caption("🕵️ Ba7ath OSINT Suite | Module Email Harvester - Extraction passive")
+
+with st.expander("💡 Conseils d'utilisation"):
+ st.markdown("""
+ ### 🎯 Meilleures pratiques
+
+ **Pages à cibler en priorité** :
+ - Pages "Contact"
+ - Pages "À propos"
+ - Pages "Équipe"
+ - Communiqués de presse
+ - Pages de support
+
+ **Optimisation** :
+ - Désactiver "Suivre les liens" pour un scan rapide
+ - Activer "Validation DNS" pour filtrer les faux emails
+ - Utiliser le mode batch pour plusieurs domaines
+
+ **Limites** :
+ - Les emails protégés par CloudFlare peuvent ne pas être détectés
+ - Les emails en images (captcha) ne sont pas extraits
+ - Respect automatique du fichier robots.txt
+
+ **Performance** :
+ - ~3 secondes par URL sans suivre les liens
+ - ~10-30 secondes avec suivi des liens (selon le site)
+ - Rate limiting automatique (2s entre requêtes)
+ """)
diff --git a/pages/12_SocialMentions.py b/pages/12_SocialMentions.py
new file mode 100644
index 0000000000000000000000000000000000000000..8258ee3a70056c2444c6296745c1e45be96bc2d0
--- /dev/null
+++ b/pages/12_SocialMentions.py
@@ -0,0 +1,63 @@
+"""
+Page Streamlit : Social Mentions Finder (Recherche mentions sur réseaux sociaux)
+Module OSINT pour Ba7ath
+"""
+
+import streamlit as st
+import sys
+import os
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'spectre_modules'))
+from social_mentions import search_social_mentions, SOCIAL_SITES
+
+st.set_page_config(page_title="Social Mentions Finder", page_icon="🔎", layout="wide")
+
+st.title("🔎 Recherche de mentions sur réseaux sociaux")
+st.caption("Recherche passive : pseudo, nom, marque, email – résultats publics via DuckDuckGo")
+
+st.markdown("---")
+
+query = st.text_input(
+ "🔍 Mot-clé (nom, pseudo, e-mail, organisation...)",
+ placeholder="elon musk / @handle / AcmeCorp / user@gmail.com"
+)
+
+platform_choices = st.multiselect(
+ "Réseaux à scanner",
+ options=list(SOCIAL_SITES.keys()),
+ default=list(SOCIAL_SITES.keys())
+)
+
+max_results = st.slider(
+ "Nb de résultats par plateforme",
+ min_value=3, max_value=30, value=10
+)
+
+cooldown = st.slider(
+ "Anti-blocage : délai entre les recherches (en s)",
+ min_value=0.5, max_value=10.0, value=1.5, step=0.5
+)
+
+if st.button("🚀 Lancer la collecte", type="primary") and query.strip():
+ st.info("⏳ Recherche en cours...")
+ results = search_social_mentions(query.strip(), platforms=platform_choices, max_results=max_results, cooldown=cooldown)
+
+ st.success("✅ Recherche terminée")
+ for platform in platform_choices:
+ hits = results.get(platform, [])
+ st.subheader(f"{platform} ({len(hits)})")
+ if not hits:
+ st.info("Aucun résultat trouvé.")
+ else:
+ for hit in hits:
+ t, u, s = hit.get("title"), hit.get("url"), hit.get("snippet")
+ if u:
+ st.markdown(f"**[{t or u}]({u})**")
+ if s:
+ st.caption(s)
+ if hit.get("error"):
+ st.error(f"Erreur : {hit['error']}")
+ st.markdown("---")
+
+st.markdown("---")
+st.caption("🕵️ Ba7ath OSINT Suite | Social Mentions Finder (via DuckDuckGo)")
diff --git a/pages/13_MaigretScan.py b/pages/13_MaigretScan.py
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/13_MaigretScan.py
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/pages/14_SocialFinder.py b/pages/14_SocialFinder.py
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/14_SocialFinder.py
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/pages/15_SpiderFoot.py b/pages/15_SpiderFoot.py
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/15_SpiderFoot.py
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/pages/16_FB_extractor.py b/pages/16_FB_extractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..81e3fb3dda3fd38b4651421d9be9cc6d53c22d50
--- /dev/null
+++ b/pages/16_FB_extractor.py
@@ -0,0 +1,1168 @@
+"""
+Ba7ath OSINT Suite - Facebook Dorking Module
+Recherche avancée Facebook avec opérateurs Google Dorking + Extraction complète
+"""
+
+import streamlit as st
+from googleapiclient.discovery import build
+import pandas as pd
+import json
+from datetime import datetime
+import time
+import os
+import requests
+from bs4 import BeautifulSoup
+import re
+from dotenv import load_dotenv
+
+load_dotenv()
+
+# ===== CONFIGURATION PAGE =====
+st.set_page_config(
+ page_title="FB extractor - Ba7ath",
+ page_icon="🔍",
+ layout="wide"
+)
+
+# ===== CSS HARMONISÉ AVEC LE DASHBOARD =====
+st.markdown("""
+
+""", unsafe_allow_html=True)
+
+# ===== INITIALISATION SESSION STATE =====
+if 'fb_search_results' not in st.session_state:
+ st.session_state['fb_search_results'] = []
+if 'fb_search_history' not in st.session_state:
+ st.session_state['fb_search_history'] = []
+if 'fb_saved_queries' not in st.session_state:
+ st.session_state['fb_saved_queries'] = []
+
+# ===== FONCTIONS UTILITAIRES =====
+def ensure_directories():
+ """Créer les dossiers nécessaires"""
+ for directory in ['reports', 'exports']:
+ os.makedirs(directory, exist_ok=True)
+
+def build_dork_query(fb_url, keywords_list, operators):
+ """Construit les requêtes Google Dorking"""
+ queries = []
+ page_name = fb_url.split('facebook.com/')[-1].strip('/')
+
+ for keyword in keywords_list:
+ query_parts = []
+
+ # Opérateur site:
+ if operators.get('use_site'):
+ query_parts.append(f'site:facebook.com/{page_name}')
+
+ # Mode de recherche
+ if operators.get('keywords_mode') == "Phrase exacte":
+ query_parts.append(f'"{keyword}"')
+ elif operators.get('keywords_mode') == "Tous les mots":
+ query_parts.append(f'allintext:{keyword}')
+ else:
+ query_parts.append(keyword)
+
+ # Opérateurs additionnels
+ if operators.get('use_inurl') and operators.get('inurl_term'):
+ query_parts.append(f'inurl:{operators["inurl_term"]}')
+
+ if operators.get('use_intext') and operators.get('intext_term'):
+ query_parts.append(f'intext:{operators["intext_term"]}')
+
+ if operators.get('use_intitle') and operators.get('intitle_term'):
+ query_parts.append(f'intitle:{operators["intitle_term"]}')
+
+ if operators.get('use_filetype') and operators.get('filetype'):
+ query_parts.append(f'filetype:{operators["filetype"]}')
+
+ # Exclusions
+ if operators.get('exclude_terms'):
+ for term in operators['exclude_terms'].split(','):
+ if term.strip():
+ query_parts.append(f'-{term.strip()}')
+
+ # Inclusions obligatoires
+ if operators.get('include_terms'):
+ for term in operators['include_terms'].split(','):
+ if term.strip():
+ query_parts.append(f'+{term.strip()}')
+
+ queries.append(' '.join(query_parts))
+
+ return queries
+
+def extract_full_content(url):
+ """
+ Extrait le contenu complet d'un post Facebook via scraping
+ """
+ try:
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Accept-Language': 'ar,en;q=0.9,fr;q=0.8',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
+ 'Accept-Encoding': 'gzip, deflate',
+ 'Connection': 'keep-alive',
+ }
+
+ response = requests.get(url, headers=headers, timeout=15)
+ response.encoding = 'utf-8'
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # Liste pour stocker les contenus trouvés
+ content_texts = []
+
+ # Méthode 1: Chercher les divs avec attributs data-ad-preview
+ for div in soup.find_all('div', {'data-ad-preview': 'message'}):
+ text = div.get_text(separator=' ', strip=True)
+ if len(text) > 50:
+ content_texts.append(text)
+
+ # Méthode 2: Chercher les éléments avec classe contenant "userContent"
+ if not content_texts:
+ for elem in soup.find_all(['div', 'p'], class_=re.compile(r'userContent|_5pbx')):
+ text = elem.get_text(separator=' ', strip=True)
+ if len(text) > 50:
+ content_texts.append(text)
+
+ # Méthode 3: Chercher tous les paragraphes conséquents
+ if not content_texts:
+ for p in soup.find_all('p'):
+ text = p.get_text(separator=' ', strip=True)
+ if len(text) > 100: # Paragraphes substantiels
+ content_texts.append(text)
+
+ # Méthode 4: Chercher les spans avec direction RTL (pour l'arabe)
+ if not content_texts:
+ for span in soup.find_all('span', dir='auto'):
+ text = span.get_text(separator=' ', strip=True)
+ if len(text) > 100:
+ content_texts.append(text)
+
+ # Méthode 5: Extraire tout le texte visible (dernier recours)
+ if not content_texts:
+ # Supprimer les scripts et styles
+ for script in soup(['script', 'style', 'header', 'footer', 'nav']):
+ script.decompose()
+
+ text = soup.get_text(separator=' ', strip=True)
+ # Nettoyer les espaces multiples
+ text = re.sub(r'\s+', ' ', text)
+ if len(text) > 200:
+ content_texts.append(text[:3000]) # Limiter à 3000 caractères
+
+ # Dédupliquer et joindre
+ if content_texts:
+ # Supprimer les doublons en gardant l'ordre
+ seen = set()
+ unique_texts = []
+ for text in content_texts:
+ if text not in seen and len(text) > 50:
+ seen.add(text)
+ unique_texts.append(text)
+
+ full_text = '\n\n'.join(unique_texts)
+
+ # Limiter la longueur totale
+ if len(full_text) > 5000:
+ full_text = full_text[:5000] + '...'
+
+ return full_text
+
+ return None
+
+ except requests.exceptions.Timeout:
+ return "⏱️ Timeout: Le serveur n'a pas répondu à temps"
+ except requests.exceptions.RequestException as e:
+ return f"❌ Erreur réseau: {str(e)[:100]}"
+ except Exception as e:
+ return f"❌ Erreur extraction: {str(e)[:100]}"
+
+def enrich_results_with_full_content(results, max_items=10):
+ """
+ Enrichit les résultats avec le contenu complet
+ """
+ enriched = []
+
+ progress_bar = st.progress(0)
+ status = st.empty()
+
+ for idx, result in enumerate(results[:max_items], 1):
+ status.text(f"📥 Extraction contenu complet... {idx}/{min(len(results), max_items)}")
+
+ # Extraire le contenu complet
+ full_content = extract_full_content(result['link'])
+
+ # Créer le résultat enrichi
+ enriched_result = result.copy()
+
+ if full_content and not full_content.startswith('❌') and not full_content.startswith('⏱️'):
+ enriched_result['full_content'] = full_content
+ enriched_result['content_length'] = len(full_content)
+ enriched_result['is_enriched'] = True
+ else:
+ enriched_result['full_content'] = result['snippet']
+ enriched_result['content_length'] = len(result['snippet'])
+ enriched_result['is_enriched'] = False
+ if full_content and (full_content.startswith('❌') or full_content.startswith('⏱️')):
+ enriched_result['extraction_error'] = full_content
+
+ enriched.append(enriched_result)
+
+ progress_bar.progress(idx / min(len(results), max_items))
+ time.sleep(1.5) # Pause pour éviter rate limiting
+
+ # Ajouter les résultats non-enrichis
+ if len(results) > max_items:
+ for result in results[max_items:]:
+ enriched.append({
+ **result,
+ 'full_content': result['snippet'],
+ 'content_length': len(result['snippet']),
+ 'is_enriched': False
+ })
+
+ progress_bar.empty()
+ status.empty()
+
+ return enriched
+
+def execute_google_search(api_key, cx, query, max_results=50, lang="ar"):
+ """Exécute la recherche Google Custom Search"""
+ try:
+ service = build("customsearch", "v1", developerKey=api_key)
+ all_results = []
+ start = 1
+
+ progress_bar = st.progress(0)
+ status = st.empty()
+
+ while len(all_results) < max_results:
+ status.text(f"🔍 Recherche en cours... {len(all_results)}/{max_results} résultats")
+
+ params = {
+ 'q': query,
+ 'cx': cx,
+ 'start': start,
+ 'num': min(10, max_results - len(all_results))
+ }
+
+ if lang != "Auto":
+ params['lr'] = f"lang_{lang}"
+
+ result = service.cse().list(**params).execute()
+
+ if 'items' not in result:
+ status.success(f"✅ Recherche terminée: {len(all_results)} résultats trouvés")
+ break
+
+ for item in result['items']:
+ all_results.append({
+ 'title': item.get('title', ''),
+ 'link': item.get('link', ''),
+ 'snippet': item.get('snippet', ''),
+ 'displayLink': item.get('displayLink', ''),
+ 'formattedUrl': item.get('formattedUrl', ''),
+ 'timestamp': datetime.now().isoformat(),
+ 'query': query
+ })
+
+ progress_bar.progress(min(len(all_results) / max_results, 1.0))
+
+ if 'queries' not in result or 'nextPage' not in result['queries']:
+ status.success(f"✅ Dernière page atteinte: {len(all_results)} résultats")
+ break
+
+ start += 10
+ time.sleep(1) # Pause pour éviter rate limiting
+
+ progress_bar.empty()
+ status.empty()
+ return all_results
+
+ except Exception as e:
+ st.error(f"❌ Erreur API: {str(e)}")
+ if "quota" in str(e).lower():
+ st.markdown("""
+
+ ⚠️ Quota API dépassé
+ Limite gratuite: 100 requêtes/jour
+ Réessayez dans 24h ou utilisez une autre clé API
+
+ """, unsafe_allow_html=True)
+ return []
+
+def save_results_to_reports(results, prefix="facebook_dorking"):
+ """Sauvegarde dans le dossier reports/ (compatible avec l'architecture Ba7ath)"""
+ ensure_directories()
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+
+ # JSON
+ json_file = f"reports/{prefix}_{timestamp}.json"
+ with open(json_file, 'w', encoding='utf-8') as f:
+ json.dump(results, f, ensure_ascii=False, indent=2)
+
+ # CSV
+ if results:
+ df = pd.DataFrame(results)
+ csv_file = f"reports/{prefix}_{timestamp}.csv"
+ df.to_csv(csv_file, index=False, encoding='utf-8-sig')
+ return json_file, csv_file
+
+ return json_file, None
+
+# ===== HEADER =====
+st.markdown("""
+
+
🔍 Facebook Dorking OSINT
+
Recherche avancée sur Facebook avec opérateurs Google
+
+ Module professionnel pour investigation sur pages Facebook publiques
+
+
+""", unsafe_allow_html=True)
+
+st.markdown("""
+### 📖 À propos de ce module
+
+Ce module vous permet d'exploiter la puissance du **Google Dorking** pour rechercher du contenu spécifique
+sur les pages Facebook publiques, sans avoir besoin d'un compte Facebook ou d'accès administrateur.
+
+**Cas d'usage typiques :**
+- 🎯 Recherche de communiqués officiels (ministères, ambassades)
+- 📰 Investigation sur des déclarations publiques
+- 🔎 Extraction de mentions spécifiques (convocations, nominations, etc.)
+- 📊 Analyse de communication d'organisations
+
+**✨ Nouvelle fonctionnalité :** Extraction du contenu complet des posts (au-delà du snippet de 160 caractères)
+
+> **Note :** Toutes les recherches respectent les limites de l'API Google (100 requêtes/jour en version gratuite).
+> Les données ne sont pas partagées avec des tiers et restent sur votre machine.
+""")
+
+# ===== SIDEBAR CONFIGURATION =====
+with st.sidebar:
+ st.markdown("### ⚙️ Configuration API")
+
+ st.markdown("""
+
+ """, unsafe_allow_html=True)
+
+ api_key = st.text_input(
+ "🔑 Clé API Google",
+ value=os.environ.get("GOOGLE_API_KEY", ""),
+ type="password",
+ help="Votre clé API Google Custom Search"
+ )
+
+ cx = st.text_input(
+ "🎯 Search Engine ID (cx)",
+ value=os.environ.get("GOOGLE_CX", ""),
+ help="ID de votre moteur de recherche personnalisé"
+ )
+
+ if st.button("🧪 Tester la connexion API"):
+ if api_key and cx:
+ try:
+ service = build("customsearch", "v1", developerKey=api_key)
+ result = service.cse().list(q="test", cx=cx, num=1).execute()
+ st.success("✅ API fonctionnelle!")
+ st.caption(f"Requêtes restantes aujourd'hui: ~{100 - len(st.session_state.get('fb_search_history', []))}")
+ except Exception as e:
+ st.error(f"❌ Erreur: {str(e)}")
+ else:
+ st.warning("⚠️ Veuillez remplir les deux champs")
+
+ st.divider()
+
+ st.markdown("### 📊 Paramètres de recherche")
+ max_results = st.slider(
+ "Résultats max par requête",
+ min_value=10,
+ max_value=100,
+ value=50,
+ step=10,
+ help="Maximum: 100 résultats (limitation Google)"
+ )
+
+ auto_save = st.checkbox(
+ "Sauvegarde automatique",
+ value=True,
+ help="Sauvegarder automatiquement dans /reports/"
+ )
+
+ st.divider()
+
+ st.markdown("### 📈 Statistiques de session")
+
+ col1, col2 = st.columns(2)
+ col1.metric("🔍 Recherches", len(st.session_state['fb_search_history']))
+ col2.metric("📄 Résultats", len(st.session_state['fb_search_results']))
+
+ if st.session_state['fb_search_history']:
+ last_search = st.session_state['fb_search_history'][-1]
+ st.caption(f"Dernière recherche: {last_search['timestamp'][:19]}")
+ st.caption(f"Résultats obtenus: {last_search['count']}")
+
+# ===== TABS PRINCIPALES =====
+tab1, tab2, tab3, tab4 = st.tabs([
+ "🎯 Recherche",
+ "📊 Résultats",
+ "📖 Guide Dorking",
+ "⚡ Templates"
+])
+
+# ===== TAB 1: RECHERCHE =====
+with tab1:
+ st.subheader("🎯 Configuration de la recherche")
+
+ # URL cible
+ col1, col2 = st.columns([3, 1])
+
+ with col1:
+ fb_url = st.text_input(
+ "🔗 URL de la page Facebook",
+ value="https://www.facebook.com/TunisieDiplo",
+ help="URL complète de la page Facebook à analyser",
+ placeholder="https://www.facebook.com/nom_page"
+ )
+
+ with col2:
+ account_type = st.selectbox(
+ "Type de compte",
+ ["Page", "Profile", "Group"],
+ help="Type de compte Facebook"
+ )
+
+ st.divider()
+
+ # Mots-clés
+ st.subheader("🔤 Mots-clés de recherche")
+
+ col1, col2 = st.columns([2, 1])
+
+ with col1:
+ keywords_mode = st.radio(
+ "Mode de recherche",
+ ["Phrase exacte", "Tous les mots", "Au moins un mot"],
+ horizontal=True,
+ help="Phrase exacte = guillemets, Tous les mots = allintext"
+ )
+
+ with col2:
+ st.markdown("**Options**")
+ rtl_support = st.checkbox("Support RTL (Arabe)", value=True)
+
+ keywords = st.text_area(
+ "Entrez vos mots-clés (un par ligne)",
+ value="استدعاء سفير\nاستدعى السفير\nسفير تونس",
+ height=120,
+ help="Chaque ligne génèrera une requête séparée"
+ )
+
+ if rtl_support:
+ st.markdown(f'{keywords}
', unsafe_allow_html=True)
+
+ st.divider()
+
+ # Opérateurs Google
+ st.subheader("🛠️ Opérateurs Google Dorking")
+
+ col1, col2, col3 = st.columns(3)
+
+ with col1:
+ st.markdown("**📍 Localisation**")
+ use_site = st.checkbox("site:", value=True, help="Limiter à un site")
+ use_inurl = st.checkbox("inurl:", help="Mot dans l'URL")
+ inurl_term = st.text_input("Terme inurl:", disabled=not use_inurl, key="inurl", placeholder="posts")
+
+ with col2:
+ st.markdown("**📝 Contenu**")
+ use_intext = st.checkbox("intext:", help="Mot dans le texte")
+ intext_term = st.text_input("Terme intext:", disabled=not use_intext, key="intext", placeholder="officiel")
+ use_intitle = st.checkbox("intitle:", help="Mot dans le titre")
+ intitle_term = st.text_input("Terme intitle:", disabled=not use_intitle, key="intitle", placeholder="وزارة")
+
+ with col3:
+ st.markdown("**🔗 Filtres avancés**")
+ use_filetype = st.checkbox("filetype:", help="Type de fichier")
+ filetype = st.selectbox(
+ "Type de fichier",
+ ["pdf", "doc", "docx", "xls", "xlsx", "jpg", "png"],
+ disabled=not use_filetype
+ )
+
+ exclude_terms = st.text_input("Exclure (séparés par ,)", placeholder="spam, publicité")
+ include_terms = st.text_input("Inclure obligatoirement", placeholder="gouvernement")
+
+ st.divider()
+
+ # Prévisualisation des requêtes
+ st.subheader("🔧 Prévisualisation des requêtes")
+
+ operators = {
+ 'use_site': use_site,
+ 'use_inurl': use_inurl,
+ 'inurl_term': inurl_term,
+ 'use_intext': use_intext,
+ 'intext_term': intext_term,
+ 'use_intitle': use_intitle,
+ 'intitle_term': intitle_term,
+ 'use_filetype': use_filetype,
+ 'filetype': filetype if use_filetype else None,
+ 'keywords_mode': keywords_mode,
+ 'exclude_terms': exclude_terms,
+ 'include_terms': include_terms
+ }
+
+ keywords_list = [k.strip() for k in keywords.split('\n') if k.strip()]
+ generated_queries = build_dork_query(fb_url, keywords_list, operators)
+
+ if generated_queries:
+ st.markdown(f"""
+
+ 📝 {len(generated_queries)} requête(s) générée(s)
+ Chaque requête consommera environ 1-10 appels API selon les résultats
+
+ """, unsafe_allow_html=True)
+
+ for i, query in enumerate(generated_queries, 1):
+ with st.expander(f"Requête {i}: {keywords_list[i-1][:50]}{'...' if len(keywords_list[i-1]) > 50 else ''}"):
+ st.markdown(f'{query}
', unsafe_allow_html=True)
+ st.caption(f"Longueur: {len(query)} caractères | Mot-clé source: **{keywords_list[i-1]}**")
+ else:
+ st.warning("⚠️ Aucune requête générée. Vérifiez vos paramètres.")
+
+ st.divider()
+
+ # Boutons d'action
+ col1, col2, col3, col4 = st.columns([2, 1, 1, 1])
+
+ with col1:
+ search_btn = st.button(
+ "🚀 Lancer la recherche",
+ type="primary",
+ disabled=not api_key or not cx or not generated_queries
+ )
+
+ with col2:
+ lang = st.selectbox(
+ "Langue",
+ ["ar", "fr", "en", "Auto"],
+ format_func=lambda x: {"ar": "🇹🇳 AR", "fr": "🇫🇷 FR", "en": "🇬🇧 EN", "Auto": "🌍 Auto"}[x]
+ )
+
+ with col3:
+ save_query_btn = st.button("💾 Sauvegarder config", disabled=not generated_queries)
+
+ with col4:
+ if st.button("🗑️ Réinitialiser"):
+ st.rerun()
+
+ # Exécution de la recherche
+ if search_btn:
+ with st.spinner("🔍 Recherche en cours..."):
+ all_results = []
+
+ # Barre de progression globale
+ main_progress = st.progress(0)
+ main_status = st.empty()
+
+ for idx, query in enumerate(generated_queries, 1):
+ main_status.info(f"📡 Requête {idx}/{len(generated_queries)}: {keywords_list[idx-1][:60]}...")
+
+ results = execute_google_search(api_key, cx, query, max_results, lang)
+ all_results.extend(results)
+
+ main_progress.progress(idx / len(generated_queries))
+
+ if idx < len(generated_queries):
+ time.sleep(2) # Pause entre requêtes
+
+ main_progress.empty()
+ main_status.empty()
+
+ # Dédupliquer par lien
+ unique_dict = {r['link']: r for r in all_results}
+ unique_results = list(unique_dict.values())
+
+ # NOUVELLE FONCTIONNALITÉ: Proposition d'extraction complète
+ if unique_results:
+ st.divider()
+ st.subheader("📥 Extraction du contenu complet")
+
+ st.markdown("""
+
+ 💡 Option avancée
+ L'API Google limite les extraits à ~160 caractères.
+ Activez l'extraction complète pour récupérer le texte intégral des posts.
+
+ """, unsafe_allow_html=True)
+
+ col1, col2 = st.columns([1, 1])
+
+ with col1:
+ extract_full = st.checkbox(
+ "✨ Extraire le contenu complet des posts",
+ value=False,
+ help="Télécharge les pages complètes (plus lent, ~2 sec/post)"
+ )
+
+ with col2:
+ if extract_full:
+ max_extract = st.slider(
+ "Nombre de posts à enrichir",
+ min_value=5,
+ max_value=min(50, len(unique_results)),
+ value=min(10, len(unique_results)),
+ help="Limiter pour éviter les timeouts"
+ )
+
+ if extract_full and st.button("🚀 Lancer l'extraction complète", type="primary"):
+ st.info(f"📥 Extraction en cours de {max_extract} post(s)...")
+
+ with st.spinner("Extraction du contenu complet..."):
+ unique_results = enrich_results_with_full_content(unique_results, max_extract)
+
+ enriched_count = sum(1 for r in unique_results if r.get('is_enriched', False))
+ st.success(f"✅ {enriched_count}/{max_extract} posts enrichis avec succès!")
+
+ # Stocker en session
+ st.session_state['fb_search_results'] = unique_results
+ st.session_state['fb_search_history'].append({
+ 'timestamp': datetime.now().isoformat(),
+ 'count': len(unique_results),
+ 'queries': generated_queries,
+ 'keywords': keywords_list
+ })
+
+ # Sauvegarde automatique
+ if auto_save and unique_results:
+ json_file, csv_file = save_results_to_reports(unique_results)
+ st.success(f"💾 Résultats sauvegardés:\n- {json_file}\n- {csv_file}")
+
+ # Affichage résumé
+ st.markdown(f"""
+
+ ✅ Recherche terminée avec succès!
+ 📊 {len(unique_results)} résultats uniques trouvés
+ 📝 {len(all_results)} résultats total
+ 🗑️ {len(all_results) - len(unique_results)} doublons supprimés
+ 🔍 {len(generated_queries)} requêtes exécutées
+
+ """, unsafe_allow_html=True)
+
+ st.balloons()
+ st.info("👉 Consultez l'onglet **📊 Résultats** pour voir les détails")
+
+ # Sauvegarde configuration
+ if save_query_btn:
+ ensure_directories()
+ config = {
+ 'timestamp': datetime.now().isoformat(),
+ 'facebook_url': fb_url,
+ 'keywords': keywords_list,
+ 'operators': operators,
+ 'queries': generated_queries
+ }
+
+ filename = f"reports/fb_config_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
+ with open(filename, 'w', encoding='utf-8') as f:
+ json.dump(config, f, ensure_ascii=False, indent=2)
+
+ st.session_state['fb_saved_queries'].append(config)
+ st.success(f"✅ Configuration sauvegardée: {filename}")
+
+# ===== TAB 2: RÉSULTATS =====
+with tab2:
+ if st.session_state.get('fb_search_results'):
+ results = st.session_state['fb_search_results']
+ df = pd.DataFrame(results)
+
+ # Compter les résultats enrichis
+ enriched_count = sum(1 for r in results if r.get('is_enriched', False))
+
+ # Métriques en haut
+ st.subheader("📊 Vue d'ensemble des résultats")
+
+ col1, col2, col3, col4 = st.columns(4)
+ col1.metric("📊 Total résultats", len(results))
+ col2.metric("🌐 Domaines uniques", df['displayLink'].nunique())
+ col3.metric("✨ Contenu complet", enriched_count)
+ col4.metric("📝 Requêtes", len(df['query'].unique()))
+
+ st.divider()
+
+ # Filtres et tri
+ col1, col2, col3 = st.columns([2, 1, 1])
+
+ with col1:
+ search_filter = st.text_input(
+ "🔎 Filtrer les résultats",
+ placeholder="Rechercher dans titres, snippets, URLs...",
+ key="filter_results"
+ )
+
+ with col2:
+ sort_option = st.selectbox(
+ "Trier par",
+ ["Pertinence (défaut)", "Titre A-Z", "URL", "Contenu complet d'abord"]
+ )
+
+ with col3:
+ items_per_page = st.selectbox(
+ "Résultats/page",
+ [10, 25, 50, 100],
+ index=1
+ )
+
+ # Application filtres
+ display_df = df.copy()
+
+ if search_filter:
+ # Recherche dans snippet OU full_content
+ if 'full_content' in df.columns:
+ mask = (
+ df['title'].str.contains(search_filter, case=False, na=False) |
+ df['snippet'].str.contains(search_filter, case=False, na=False) |
+ df['full_content'].str.contains(search_filter, case=False, na=False) |
+ df['link'].str.contains(search_filter, case=False, na=False)
+ )
+ else:
+ mask = (
+ df['title'].str.contains(search_filter, case=False, na=False) |
+ df['snippet'].str.contains(search_filter, case=False, na=False) |
+ df['link'].str.contains(search_filter, case=False, na=False)
+ )
+ display_df = df[mask]
+
+ # Tri
+ if sort_option == "Titre A-Z":
+ display_df = display_df.sort_values('title')
+ elif sort_option == "URL":
+ display_df = display_df.sort_values('link')
+ elif sort_option == "Contenu complet d'abord":
+ if 'is_enriched' in display_df.columns:
+ display_df = display_df.sort_values('is_enriched', ascending=False)
+
+ st.info(f"📋 Affichage de **{len(display_df)}** résultat(s) sur **{len(results)}** total")
+
+ # Pagination
+ total_items = len(display_df)
+ total_pages = (total_items - 1) // items_per_page + 1 if total_items > 0 else 1
+
+ if total_pages > 1:
+ page = st.selectbox(
+ f"Page (1-{total_pages})",
+ range(1, total_pages + 1),
+ format_func=lambda x: f"Page {x}/{total_pages}"
+ )
+ start_idx = (page - 1) * items_per_page
+ end_idx = min(start_idx + items_per_page, total_items)
+ page_df = display_df.iloc[start_idx:end_idx]
+ else:
+ page_df = display_df
+
+ st.divider()
+
+ # Affichage des résultats
+ for idx, row in page_df.iterrows():
+ # Déterminer quel contenu afficher
+ is_enriched = row.get('is_enriched', False)
+ display_content = row.get('full_content', row['snippet'])
+ content_length = row.get('content_length', len(display_content))
+
+ st.markdown(f"""
+
+
+
+ {row['title']}
+
+ {f'✨ CONTENU COMPLET ' if is_enriched else ''}
+
+
+ 🔗 {row['formattedUrl']} • 📏 {content_length} caractères
+
+
+ {display_content}
+
+
+
+ 📅 {row['timestamp'][:19].replace('T', ' ')}
+
+
+ 🔍 Requête: {row['query'][:60]}...
+
+
+
+ """, unsafe_allow_html=True)
+
+ # Afficher erreur d'extraction si présente
+ if 'extraction_error' in row:
+ st.caption(f"⚠️ {row['extraction_error']}")
+
+ st.divider()
+
+ # Export
+ st.subheader("💾 Export des données")
+
+ col1, col2, col3, col4 = st.columns(4)
+
+ with col1:
+ json_data = display_df.to_json(orient='records', force_ascii=False, indent=2)
+ st.download_button(
+ "📄 Télécharger JSON",
+ json_data,
+ f"ba7ath_fb_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
+ "application/json"
+ )
+
+ with col2:
+ csv_data = display_df.to_csv(index=False, encoding='utf-8-sig')
+ st.download_button(
+ "📊 Télécharger CSV",
+ csv_data,
+ f"ba7ath_fb_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
+ "text/csv"
+ )
+
+ with col3:
+ # Export liste URLs
+ urls = "\n".join(display_df['link'].tolist())
+ st.download_button(
+ "🔗 Liste URLs",
+ urls,
+ f"urls_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
+ "text/plain"
+ )
+
+ with col4:
+ if st.button("💾 Sauvegarder localement"):
+ json_f, csv_f = save_results_to_reports(display_df.to_dict('records'))
+ st.success(f"✅ Sauvegardé!\n{json_f}\n{csv_f}")
+
+ # Statistiques avancées
+ with st.expander("📈 Statistiques avancées"):
+ col1, col2 = st.columns(2)
+
+ with col1:
+ st.markdown("**Distribution par domaine**")
+ domain_counts = display_df['displayLink'].value_counts().head(10)
+ st.bar_chart(domain_counts)
+
+ with col2:
+ st.markdown("**Longueur des contenus**")
+ if 'content_length' in display_df.columns:
+ st.line_chart(display_df['content_length'])
+ else:
+ display_df['snippet_len'] = display_df['snippet'].str.len()
+ st.line_chart(display_df['snippet_len'])
+
+ else:
+ st.markdown("""
+
+
ℹ️ Aucun résultat disponible
+
Lancez une recherche dans l'onglet 🎯 Recherche pour voir les résultats ici.
+
+ """, unsafe_allow_html=True)
+
+ if st.button("🔄 Charger un exemple de démonstration"):
+ st.session_state['fb_search_results'] = [
+ {
+ 'title': 'Exemple - Ministère des Affaires Étrangères de Tunisie',
+ 'link': 'https://www.facebook.com/TunisieDiplo/posts/123456789',
+ 'snippet': 'استدعاء سفير الجمهورية التونسية في باريس للتشاور حول القضايا الدبلوماسية...',
+ 'displayLink': 'facebook.com',
+ 'formattedUrl': 'www.facebook.com › TunisieDiplo › posts',
+ 'timestamp': datetime.now().isoformat(),
+ 'query': 'site:facebook.com/TunisieDiplo "استدعاء سفير"'
+ }
+ ]
+ st.rerun()
+
+# ===== TAB 3: GUIDE =====
+with tab3:
+ st.subheader("📖 Guide complet des opérateurs Google Dorking")
+
+ st.markdown("""
+ Les opérateurs Google (Google Dorks) sont des commandes spéciales qui affinent vos recherches.
+ Combinez-les pour des résultats ultra-précis.
+ """)
+
+ # Guide par catégorie
+ operators_guide = {
+ "🎯 Ciblage de domaine": {
+ "site:": {
+ "desc": "Limite la recherche à un domaine/site spécifique",
+ "ex": "site:facebook.com/TunisieDiplo",
+ "usage": "Rechercher uniquement sur une page Facebook donnée"
+ },
+ "inurl:": {
+ "desc": "Le mot doit apparaître dans l'URL",
+ "ex": "inurl:posts",
+ "usage": "Trouver des publications (posts dans l'URL)"
+ }
+ },
+ "📝 Contenu textuel": {
+ "intext:": {
+ "desc": "Le mot doit être dans le texte de la page",
+ "ex": 'intext:"استدعاء سفير"',
+ "usage": "Chercher dans le contenu réel de la page"
+ },
+ "allintext:": {
+ "desc": "Tous les mots doivent être dans le texte",
+ "ex": "allintext:ambassador tunisia recall",
+ "usage": "Tous les termes présents obligatoirement"
+ },
+ "intitle:": {
+ "desc": "Le mot doit être dans le titre",
+ "ex": "intitle:وزارة",
+ "usage": "Rechercher dans les titres uniquement"
+ }
+ },
+ "📁 Fichiers et formats": {
+ "filetype:": {
+ "desc": "Chercher un type de fichier spécifique",
+ "ex": "filetype:pdf rapport",
+ "usage": "Trouver des PDF, DOC, XLS, etc."
+ }
+ },
+ "🎛️ Modificateurs": {
+ '"phrase"': {
+ "desc": "Recherche de phrase exacte",
+ "ex": '"استدعاء سفير تونس"',
+ "usage": "La phrase doit apparaître telle quelle"
+ },
+ "-terme": {
+ "desc": "Exclure un mot des résultats",
+ "ex": "tunisie -football",
+ "usage": "Éliminer résultats non pertinents"
+ },
+ "OR": {
+ "desc": "L'un ou l'autre terme",
+ "ex": "tunisia OR tunisie",
+ "usage": "Recherche multilingue"
+ },
+ "*": {
+ "desc": "Joker (remplace n'importe quel mot)",
+ "ex": "tunisie * ambassadeur",
+ "usage": "Chercher avec mot inconnu au milieu"
+ }
+ }
+ }
+
+ for category, ops in operators_guide.items():
+ st.markdown(f"### {category}")
+
+ for op, details in ops.items():
+ with st.expander(f"**`{op}`** - {details['desc']}"):
+ col1, col2 = st.columns(2)
+
+ with col1:
+ st.markdown("**📋 Exemple:**")
+ st.code(details['ex'], language="text")
+
+ with col2:
+ st.markdown("**💡 Utilisation:**")
+ st.info(details['usage'])
+
+ st.divider()
+
+ # Exemples avancés
+ st.subheader("🔥 Exemples de recherches OSINT avancées")
+
+ examples = [
+ {
+ "title": "Convocations d'ambassadeurs tunisiens",
+ "query": 'site:facebook.com/TunisieDiplo "استدعاء سفير" OR "recall ambassador"',
+ "explain": "Recherche bilingue (AR/EN) de convocations sur la page du ministère"
+ },
+ {
+ "title": "Communiqués officiels sans publicités",
+ "query": 'site:facebook.com/TunisieDiplo "بيان رسمي" -إعلان -sponsored',
+ "explain": "Communiqués officiels en excluant les contenus publicitaires"
+ },
+ {
+ "title": "Documents PDF du ministère",
+ "query": 'site:diplomatie.gov.tn filetype:pdf "rapport annuel"',
+ "explain": "Rapports PDF officiels du site gouvernemental"
+ },
+ {
+ "title": "Mentions de pays spécifiques",
+ "query": 'site:facebook.com/TunisieDiplo (فرنسا OR ألمانيا OR إيطاليا)',
+ "explain": "Posts mentionnant France, Allemagne ou Italie"
+ }
+ ]
+
+ for ex in examples:
+ with st.expander(f"🎯 {ex['title']}"):
+ st.code(ex['query'], language="text")
+ st.caption(f"💭 Explication: {ex['explain']}")
+ if st.button(f"📋 Copier cette requête", key=f"copy_{ex['title']}"):
+ st.toast("✅ Requête copiée dans le presse-papier!")
+
+# ===== TAB 4: TEMPLATES =====
+with tab4:
+ st.subheader("⚡ Templates de requêtes pré-configurés")
+
+ st.markdown("""
+ Utilisez ces templates prêts à l'emploi pour vos investigations courantes.
+ Cliquez sur un template pour le charger dans l'onglet Recherche.
+ """)
+
+ templates = {
+ "🇹🇳 Diplomatie Tunisienne": [
+ {
+ "name": "Convocations ambassadeurs",
+ "url": "https://www.facebook.com/TunisieDiplo",
+ "keywords": ["استدعاء سفير", "recall ambassador", "convocation ambassadeur"],
+ "desc": "Recherche de convocations d'ambassadeurs tunisiens"
+ },
+ {
+ "name": "Communiqués officiels",
+ "url": "https://www.facebook.com/TunisieDiplo",
+ "keywords": ["بيان رسمي", "communiqué officiel", "déclaration"],
+ "desc": "Communications officielles du ministère"
+ },
+ {
+ "name": "Relations bilatérales",
+ "url": "https://www.facebook.com/TunisieDiplo",
+ "keywords": ["علاقات ثنائية", "coopération", "اتفاقية"],
+ "desc": "Accords et coopération internationale"
+ }
+ ],
+ "📰 Investigation Médiatique": [
+ {
+ "name": "Scandales et controverses",
+ "url": "https://www.facebook.com/",
+ "keywords": ["فضيحة", "scandale", "controverse"],
+ "desc": "Recherche de contenus sensibles"
+ },
+ {
+ "name": "Déclarations officielles",
+ "url": "https://www.facebook.com/",
+ "keywords": ["تصريح رسمي", "déclaration", "statement"],
+ "desc": "Déclarations de personnalités"
+ }
+ ]
+ }
+
+ for category, tmpl_list in templates.items():
+ st.markdown(f"### {category}")
+
+ cols = st.columns(2)
+
+ for idx, tmpl in enumerate(tmpl_list):
+ with cols[idx % 2]:
+ with st.container():
+ st.markdown(f"**{tmpl['name']}**")
+ st.caption(tmpl['desc'])
+
+ with st.expander("👁️ Détails"):
+ st.write(f"**URL:** {tmpl['url']}")
+ st.write(f"**Mots-clés:**")
+ for kw in tmpl['keywords']:
+ st.code(kw)
+
+ if st.button(f"📥 Utiliser ce template", key=f"use_{category}_{idx}"):
+ st.session_state['loaded_template'] = tmpl
+ st.success(f"✅ Template '{tmpl['name']}' chargé!")
+ st.info("💡 Passez à l'onglet **🎯 Recherche** pour l'utiliser")
+
+ st.divider()
+
+# ===== FOOTER =====
+st.divider()
+st.markdown("""
+
+
Ba7ath OSINT Suite - Module Facebook Dorking v1.1
+
+ Développé pour le journalisme d'investigation en Tunisie 🇹🇳
+
+
+ ⚠️ Utilisation responsable uniquement • Respectez les lois sur la protection des données
+
+
+ 📧 Support: ba7ath@protonmail.com | 💻 Ba7ath Project
+
+
+""", unsafe_allow_html=True)
+
+# Initialiser les dossiers au démarrage
+ensure_directories()
diff --git a/pages/1_BUS.py b/pages/1_BUS.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef113f6013d617e8d10ba5ef04af3d9fb773b95b
--- /dev/null
+++ b/pages/1_BUS.py
@@ -0,0 +1,133 @@
+import re
+import streamlit as st
+import subprocess
+import os
+import sys
+from datetime import datetime
+import pandas as pd
+
+# Définition du chemin des outils externes
+if getattr(sys, 'frozen', False):
+ # En mode exécutable (PyInstaller)
+ EXT_TOOLS_DIR = os.path.join(os.path.dirname(sys.executable), 'outils_externes')
+else:
+ # En mode développement
+ EXT_TOOLS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+SHERLOCK_DIR = os.path.join(EXT_TOOLS_DIR, 'sherlock')
+ALL_SITES_PATH = os.path.join(SHERLOCK_DIR, 'all_sites.txt')
+SHERLOCK_SCRIPT = os.path.join(SHERLOCK_DIR, 'sherlock_project', 'sherlock.py')
+
+st.set_page_config(page_title="BUS", page_icon="🔍", layout="wide")
+
+# Charger la liste des sites
+try:
+ with open(ALL_SITES_PATH, 'r', encoding='utf-8') as f:
+ ALL_SITES = sorted(set(line.strip() for line in f if line.strip()))
+except Exception as e:
+ ALL_SITES = []
+ st.error(f"Erreur de lecture de {ALL_SITES_PATH}: {e}")
+
+CATEGORIES = {
+ "Réseaux sociaux": ["Facebook", "Twitter", "Instagram", "LinkedIn", "TikTok", "Snapchat", "Reddit", "VK", "Tumblr", "Pinterest", "YouTube"],
+ "Développement/Code": ["GitHub", "GitLab", "BitBucket", "Codewars", "Codepen", "StackOverflow"],
+ "Crypto/Finance": ["Venmo", "Coinvote", "CashApp", "Patreon", "BuyMeACoffee", "Revolut"],
+ "Musique/Vidéo": ["SoundCloud", "Spotify", "Bandcamp", "MixCloud", "DailyMotion", "Vimeo"],
+ "Divers/Forums": ["Quora", "4chan", "Disqus", "Forum Ophilia", "BoardGameGeek", "Warrior Forum"],
+}
+
+st.header("BUS – Recherche avancée")
+
+if "selected_sites" not in st.session_state:
+ st.session_state["selected_sites"] = []
+
+if "last_result" not in st.session_state:
+ st.session_state["last_result"] = ""
+
+if "last_found_links" not in st.session_state:
+ st.session_state["last_found_links"] = {}
+
+type_choice = st.selectbox("Type de recherche :", ["Tout", "Par catégorie"])
+
+if type_choice == "Tout":
+ if not st.session_state["selected_sites"] or set(st.session_state["selected_sites"]) != set(ALL_SITES):
+ st.session_state["selected_sites"] = ALL_SITES
+elif type_choice == "Par catégorie":
+ category = st.selectbox("Catégorie :", list(CATEGORIES.keys()))
+ cat_sites = [site for site in CATEGORIES[category] if site in ALL_SITES]
+ if not st.session_state["selected_sites"] or set(st.session_state["selected_sites"]) != set(cat_sites):
+ st.session_state["selected_sites"] = cat_sites
+
+col1, col2 = st.columns([1, 4])
+with col1:
+ if st.button("Tout sélectionner"):
+ if type_choice == "Tout":
+ st.session_state["selected_sites"] = ALL_SITES
+ elif type_choice == "Par catégorie":
+ st.session_state["selected_sites"] = cat_sites
+ if st.button("Tout désélectionner"):
+ st.session_state["selected_sites"] = []
+
+selected_sites = st.multiselect(
+ "Plateformes à analyser :", ALL_SITES,
+ key="selected_sites"
+)
+
+username = st.text_input("Username à tester :", key="ba7ath_input")
+timeout = st.slider("Timeout maximum par site (secondes) :", min_value=2, max_value=20, value=11)
+
+if st.button("Lancer Ba7ath Username Search", key="ba7ath_btn"):
+ if not username or not selected_sites:
+ st.warning("Remplissez tous les champs.")
+ else:
+ if len(selected_sites) == len(ALL_SITES):
+ sites_args = ""
+ else:
+ sites_args = " ".join([f'--site "{site}"' for site in selected_sites])
+ command = (
+ f'"{sys.executable}" "{SHERLOCK_SCRIPT}" '
+ f'{username} {sites_args} --timeout {timeout} --print-found'
+ )
+ st.info(f"Commande lancée : {command}")
+ result = subprocess.getoutput(command)
+ st.session_state["last_result"] = result
+ found_links = {}
+ for line in result.splitlines():
+ line = line.strip()
+ if line.startswith("[+]") and ":" in line and "http" in line:
+ site = line.split(":", 1)[0][3:].strip()
+ urls = re.findall(r"(https?://[^\s\]\)]+)", line)
+ if urls:
+ url = max(urls, key=len)
+ found_links[site] = url
+ st.session_state["last_found_links"] = found_links
+
+found_links = st.session_state.get("last_found_links", {})
+result = st.session_state.get("last_result", "")
+
+if found_links:
+ st.success(f"{len(found_links)} résultats trouvés :")
+ st.markdown("| Plateforme | Lien | Date | Statut |\n|---|---|---|---|")
+ date = datetime.now().strftime("%d/%m/%Y %H:%M")
+ results = []
+ for site, url in found_links.items():
+ st.markdown(f"| {site} | [{url}]({url}) | {date} | Trouvé |")
+ results.append({
+ "Plateforme": site,
+ "Lien": url,
+ "Date": date,
+ "Statut": "Trouvé"
+ })
+ df = pd.DataFrame(results)
+ csv = df.to_csv(index=False).encode("utf-8")
+ st.download_button(
+ label="Télécharger les résultats en CSV",
+ data=csv,
+ file_name=f"ba7ath_{username}_results.csv",
+ mime="text/csv"
+ )
+else:
+ st.warning("Aucun résultat trouvé sur les plateformes sélectionnées.")
+
+with st.expander("Afficher la sortie brute Ba7ath"):
+ st.text(result)
diff --git a/pages/2_MultiComptes.py b/pages/2_MultiComptes.py
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/2_MultiComptes.py
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/pages/3_Leaks.py b/pages/3_Leaks.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a9972c1a1265674e337c5e46c05f95e1164d560
--- /dev/null
+++ b/pages/3_Leaks.py
@@ -0,0 +1,84 @@
+import streamlit as st
+import webbrowser
+import requests
+import pandas as pd
+
+st.header("Recherche de leaks / Data Breach par email ou username")
+
+target = st.text_input("Email ou username à vérifier (HaveIBeenPwned, XposedOrNot, LeakCheck):", key="leaks_input")
+
+# HIBP (web)
+st.markdown("⚠️ L'utilisation de l'API HIBP nécessite une clé — mais vous pouvez vérifier manuellement sur le site :", unsafe_allow_html=True)
+if st.button("Vérifier sur le site HaveIBeenPwned", key="hibp_btn"):
+ if not target:
+ st.warning("Veuillez entrer un email à vérifier.")
+ else:
+ hibp_url = f"https://haveibeenpwned.com/account/{target}"
+ st.info(f"Ouvre la page HIBP dans un nouvel onglet pour : `{target}`")
+ st.markdown(f"[Lien direct vers HIBP avec ce compte ➜]({hibp_url})", unsafe_allow_html=True)
+ webbrowser.open_new_tab(hibp_url)
+
+st.markdown("---")
+
+# XposedOrNot (email) - API ouverte
+if st.button("Vérifier sur XposedOrNot API", key="xon_btn"):
+ if not target or "@" not in target:
+ st.warning("Veuillez entrer un email (format ...) pour XposedOrNot.")
+ else:
+ api_url = f"https://api.xposedornot.com/v1/check-email/{target}"
+ resp = requests.get(api_url)
+ if resp.status_code == 200:
+ info = resp.json()
+ if info.get("breaches"):
+ st.success(f"{target} trouvé dans {len(info['breaches'])} breaches (XposedOrNot) !")
+ df = pd.DataFrame(info["breaches"])
+ st.dataframe(df)
+ st.download_button(
+ label="Télécharger en CSV (XposedOrNot)",
+ data=df.to_csv(index=False).encode("utf-8"),
+ file_name=f"xposedornot_{target}_results.csv",
+ mime="text/csv"
+ )
+ else:
+ st.info(f"Aucun leak trouvé pour {target} sur XposedOrNot.")
+ else:
+ st.error(f"Erreur API ({resp.status_code}).")
+
+st.markdown("---")
+
+# LeakCheck API Publique (sans clé minimum, peut aussi ajouter version clé ensuite)
+if st.button("Vérifier sur LeakCheck API Publique", key="lc_public_btn"):
+ if not target:
+ st.warning("Veuillez entrer un email ou username à vérifier (LeakCheck).")
+ else:
+ api_url = f"https://leakcheck.io/api/public?check={target}"
+ resp = requests.get(api_url)
+ if resp.status_code == 200:
+ info = resp.json()
+ if info.get("success") and info.get("found", 0) > 0:
+ st.success(f"{target} trouvé dans {info['found']} leaks (LeakCheck) !")
+ sources = info.get("sources", [])
+ st.dataframe(pd.DataFrame(sources))
+ st.download_button(
+ label="Télécharger les sources en CSV (LeakCheck)",
+ data=pd.DataFrame(sources).to_csv(index=False).encode("utf-8"),
+ file_name=f"leakcheck_{target}_results.csv",
+ mime="text/csv"
+ )
+ st.markdown(
+ 'Powered by LeakCheck ',
+ unsafe_allow_html=True
+ )
+ else:
+ st.info(f"Aucun leak trouvé pour {target} sur LeakCheck.")
+ else:
+ st.error(f"Erreur API LeakCheck ({resp.status_code}).")
+
+st.markdown("---")
+st.markdown("""
+### Alternatives pro :
+- **LeakCheck API avancée** (clé API requise pour recherches premium)
+- **OSINTLeak** (Starter free plan, inscription API)
+
+Powered by LeakCheck.io
+""", unsafe_allow_html=True)
diff --git a/pages/4_YouTube.py b/pages/4_YouTube.py
new file mode 100644
index 0000000000000000000000000000000000000000..9318bf0fd2ccbf08115cffb2eaedfce42c8f5c50
--- /dev/null
+++ b/pages/4_YouTube.py
@@ -0,0 +1,123 @@
+import streamlit as st
+import requests
+import pandas as pd
+from datetime import datetime
+import folium
+
+st.set_page_config(layout="wide")
+st.header("YouTube OSINT : recherche avancée, affichage map & export")
+
+import os
+from dotenv import load_dotenv
+
+load_dotenv()
+default_yt_key = os.getenv("YOUTUBE_API_KEY", "")
+
+api_key = default_yt_key
+query = st.text_input("Mot-clé / hashtag (ex: #osint) :", key="yt_query")
+channel_id = st.text_input("ID de chaîne (optionnel) :", key="yt_channelid")
+place = st.text_input("Lieu (ville, région, pays, optionnel) :", key="yt_place")
+radius = st.text_input("Rayon (ex: 20km)", value="20km")
+max_results = st.slider("Nombre max résultats", 5, 50, 15)
+start_date = st.date_input("Date début", value=datetime(2023, 1, 1))
+end_date = st.date_input("Date fin", value=datetime.now())
+
+def geocode(place, limit=3):
+ url = f"https://nominatim.openstreetmap.org/search?format=json&q={place}"
+ headers = {"User-Agent": "Ba7ath OSINT Tool"}
+ resp = requests.get(url, headers=headers)
+ if resp.status_code == 200 and "application/json" in resp.headers.get("Content-Type", ""):
+ try:
+ data = resp.json()
+ if data:
+ # Propose choix si plusieurs résultats
+ options = [f"{d['display_name']} ({d['lat']}, {d['lon']})" for d in data[:limit]]
+ idx = st.selectbox("Sélectionner le lieu exact :", options, index=0)
+ dmatch = data[options.index(idx)]
+ lat, lon = dmatch['lat'], dmatch['lon']
+ return f"{lat},{lon}"
+ else:
+ return None
+ except Exception:
+ return None
+ else:
+ return None
+
+if st.button("Rechercher sur YouTube"):
+ # Géocodage si lieu fourni
+ location = geocode(place) if place else None
+ published_after = start_date.strftime("%Y-%m-%dT00:00:00Z")
+ published_before = end_date.strftime("%Y-%m-%dT23:59:59Z")
+
+ url = (
+ f"https://www.googleapis.com/youtube/v3/search?"
+ f"part=snippet&type=video&q={query or ''}"
+ f"{'&channelId='+channel_id if channel_id else ''}"
+ f"{'&location='+location if location else ''}"
+ f"{'&locationRadius='+radius if location else ''}"
+ f"&maxResults={max_results}&key={api_key}"
+ f"&publishedAfter={published_after}&publishedBefore={published_before}"
+ )
+
+ resp = requests.get(url)
+ if resp.status_code == 200:
+ items = resp.json().get("items", [])
+ if items:
+ rows = []
+ points = []
+ for video in items:
+ snippet = video["snippet"]
+ video_id = video["id"]["videoId"]
+ title = snippet["title"]
+ channel = snippet["channelTitle"]
+ published = snippet["publishedAt"][:10]
+ url_vid = f"https://youtube.com/watch?v={video_id}"
+ thumb = snippet["thumbnails"]["default"]["url"]
+ geo = None
+ if location and "geo" in video:
+ geo = (video["geo"]["latitude"], video["geo"]["longitude"])
+ points.append({"lat": geo[0], "lon": geo[1], "popup": title})
+ rows.append({
+ "Miniature": f"",
+ "Titre": f"[{title}]({url_vid})",
+ "Chaîne": channel,
+ "Date": published,
+ "Lien brut": url_vid,
+ "Miniature URL": thumb
+ })
+ df = pd.DataFrame(rows)
+
+ st.markdown("### Résultats (liens cliquables & miniatures)")
+ st.write(df.to_markdown(index=False), unsafe_allow_html=True)
+ st.download_button(
+ "Télécharger résultats CSV",
+ df.to_csv(index=False).encode("utf-8"),
+ file_name="youtube_osint_total.csv",
+ mime="text/csv"
+ )
+
+ # Carte interactive si points GPS disponibles
+ if place and points:
+ st.markdown("### Carte interactive des vidéos géolocalisées")
+ map = folium.Map(location=[float(points[0]["lat"]), float(points[0]["lon"])], zoom_start=8)
+ for pt in points:
+ folium.Marker([float(pt["lat"]), float(pt["lon"])], popup=pt["popup"]).add_to(map)
+ st.components.v1.html(map._repr_html_(), height=500)
+ else:
+ st.info("Aucune vidéo trouvée pour les critères donnés.")
+ else:
+ st.error(f"Erreur API : {resp.status_code} - {resp.text}")
+
+st.markdown("""
+---
+**Fonctions incluses** :
+- Recherche par mot-clé, hashtag, chaîne, lieu (conversion automatique)
+- Liens cliquables YouTube
+- Miniatures vidéo
+- Filtrage temporel
+- Export CSV
+- Suggestions de lieux si ambiguïté
+- Carte interactive pour les vidéos géolocalisées
+
+**Astuces** : Utilise l’ID de chaîne officiel pour cibler un créateur (dispo dans l’URL d’une chaîne Youtube).
+""")
diff --git a/pages/5_GeoFinder.py b/pages/5_GeoFinder.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5fc84096794023c1b2dbb1747767b337477dadb
--- /dev/null
+++ b/pages/5_GeoFinder.py
@@ -0,0 +1,128 @@
+import streamlit as st
+import exifread
+import folium
+import requests
+from io import BytesIO
+
+st.header("GeoFinder | Analyse & géolocalisation d’images/vidéos en ligne ou locale")
+import os
+from dotenv import load_dotenv
+
+load_dotenv()
+
+YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY", "")
+
+def extract_exif_data(tags):
+ exif_info = {}
+ exif_info["Date de prise de vue"] = str(tags.get("EXIF DateTimeOriginal", ""))
+ exif_info["Date de modification"] = str(tags.get("Image DateTime", ""))
+ exif_info["Appareil"] = f"{tags.get('Image Make','')} {tags.get('Image Model','')}"
+ exif_info["Focale"] = str(tags.get("EXIF FocalLength", ""))
+ exif_info["Ouverture"] = str(tags.get("EXIF FNumber", ""))
+ exif_info["ISO"] = str(tags.get("EXIF ISOSpeedRatings", ""))
+ exif_info["Flash"] = str(tags.get("EXIF Flash", ""))
+ exif_info["Dimensions"] = f"{tags.get('EXIF ExifImageWidth','')} x {tags.get('EXIF ExifImageLength','')}"
+ exif_info["Balance des blancs"] = str(tags.get("EXIF WhiteBalance", ""))
+ exif_info["Modèle"] = str(tags.get("Image Model", ""))
+ exif_info["Marque"] = str(tags.get("Image Make", ""))
+ return exif_info
+
+tab1, tab2 = st.tabs(["Image locale", "Image en ligne/vidéo"])
+
+with tab1:
+ img_file = st.file_uploader("Télécharge une image (JPEG)", type=["jpg", "jpeg"])
+ if img_file:
+ tags = exifread.process_file(img_file)
+ def get_float(tag):
+ if not tag: return None
+ parts = str(tag).replace('[','').replace(']','').split(',')
+ try: return float(parts[0])
+ except: return None
+ lat = get_float(tags.get('GPS GPSLatitude'))
+ lon = get_float(tags.get('GPS GPSLongitude'))
+ exif_info = extract_exif_data(tags)
+ st.write("Infos EXIF clés :", exif_info)
+ st.write("Toutes les métadonnées EXIF :", tags)
+ if lat and lon:
+ st.success(f"Coordonnées GPS: {lat}, {lon}")
+ map = folium.Map(location=[lat, lon], zoom_start=12)
+ folium.Marker([lat, lon], popup="Photo géolocalisée").add_to(map)
+ st.components.v1.html(map._repr_html_(), height=400)
+ else:
+ st.info("Pas de coordonnées GPS trouvées dans cette image.")
+
+with tab2:
+ url = st.text_input("URL d’une image (jpg/jpeg) ou vidéo YouTube :", key="in_url")
+ if st.button("Analyser ce média en ligne"):
+ if url.lower().endswith((".jpg",".jpeg")):
+ try:
+ resp = requests.get(url)
+ if resp.ok:
+ tags = exifread.process_file(BytesIO(resp.content))
+ lat, lon = None, None
+ def get_float(tag):
+ if not tag: return None
+ parts = str(tag).replace('[','').replace(']','').split(',')
+ try: return float(parts[0])
+ except: return None
+ lat = get_float(tags.get('GPS GPSLatitude'))
+ lon = get_float(tags.get('GPS GPSLongitude'))
+ exif_info = extract_exif_data(tags)
+ st.write("Infos EXIF clés :", exif_info)
+ st.write("Métadonnées EXIF :", tags)
+ if lat and lon:
+ st.success(f"Coordonnées GPS: {lat}, {lon}")
+ map = folium.Map(location=[lat, lon], zoom_start=12)
+ folium.Marker([lat, lon], popup="Image géolocalisée").add_to(map)
+ st.components.v1.html(map._repr_html_(), height=400)
+ else:
+ st.info("Pas de coordonnées GPS dans cette image en ligne.")
+ else:
+ st.warning("Impossible de récupérer l'image depuis l’URL. Vérifie le lien.")
+ except Exception as e:
+ st.error(f"Erreur lors de l’analyse de l’image en ligne: {e}")
+ elif "youtube.com/watch" in url or "youtu.be/" in url:
+ import re
+ match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11})", url)
+ video_id = match.group(1) if match else None
+ if video_id:
+ api_url = (
+ f"https://www.googleapis.com/youtube/v3/videos?part=recordingDetails,snippet,contentDetails"
+ f"&id={video_id}&key={YOUTUBE_API_KEY}"
+ )
+ resp = requests.get(api_url)
+ if resp.status_code == 200:
+ data = resp.json()
+ item = data.get("items", [{}])[0]
+ details = item.get("recordingDetails", {})
+ snippet = item.get("snippet", {})
+ content = item.get("contentDetails", {})
+ geo = details.get("location", {})
+ lat, lon = geo.get("latitude"), geo.get("longitude")
+ video_info = {
+ "Titre": snippet.get("title", ""),
+ "Auteur (Chaîne)": snippet.get("channelTitle",""),
+ "Date de publication": snippet.get("publishedAt",""),
+ "Durée": content.get("duration",""),
+ "Description": snippet.get("description",""),
+ "Lieu (YouTube Rec)": details.get("locationDescription","")
+ }
+ st.write("Infos vidéo YouTube :", video_info)
+ if lat and lon:
+ st.success(f"Géoloc trouvée: lat {lat}, lon {lon}")
+ map = folium.Map(location=[lat, lon], zoom_start=10)
+ folium.Marker([lat, lon], popup=video_info["Titre"]).add_to(map)
+ st.components.v1.html(map._repr_html_(), height=400)
+ else:
+ st.info("Pas de données GPS vidéo publiques associées à cette vidéo.")
+ else:
+ st.error("Impossible de consulter l’API YouTube pour cette vidéo.")
+ else:
+ st.warning("Impossible d’extraire l’ID de la vidéo depuis l’URL fournie.")
+ else:
+ st.warning("Format non reconnu. Utilise une image .jpg/.jpeg ou une vidéo YouTube.")
+
+st.markdown("---")
+st.markdown("""
+*GeoFinder analyse et extrait maintenant les infos clés d’image ou vidéo : date de prise de vue, appareil, auteur, GPS, durée, description…*
+""")
diff --git a/pages/6_Entity_extraction.py.disabled b/pages/6_Entity_extraction.py.disabled
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/6_Entity_extraction.py.disabled
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/pages/7_FaceFinderOSINT.py b/pages/7_FaceFinderOSINT.py
new file mode 100644
index 0000000000000000000000000000000000000000..0848a5ffb0c22fe70ab40500a8b55bd3f148a0d3
--- /dev/null
+++ b/pages/7_FaceFinderOSINT.py
@@ -0,0 +1,182 @@
+import streamlit as st
+import face_recognition
+from PIL import Image, ImageDraw
+import io
+import os
+import requests
+import json
+from bs4 import BeautifulSoup
+import time
+import urllib.parse
+
+import os
+from dotenv import load_dotenv
+
+load_dotenv()
+
+IMGBB_API_KEY = os.getenv("IMGBB_API_KEY", "")
+
+API_CONFIG = {
+ "SerpApi": {"quota": 250, "count": 0, "api_key": os.getenv("SERPAPI_KEY_FACEFINDER", "")},
+ "Zenserp": {"quota": 50, "count": 0, "api_key": os.getenv("ZENSERP_API_KEY", "")}
+}
+
+COUNTER_FILE = "reverse_api_counts.json"
+if os.path.exists(COUNTER_FILE):
+ with open(COUNTER_FILE, "r") as f:
+ counts = json.load(f)
+ for k in API_CONFIG:
+ API_CONFIG[k]["count"] = counts.get(k, 0)
+else:
+ counts = {k: 0 for k in API_CONFIG}
+
+def save_counts():
+ with open(COUNTER_FILE, "w") as f:
+ json.dump({k: API_CONFIG[k]["count"] for k in API_CONFIG}, f)
+
+def upload_image_imgbb(image_path):
+ url = "https://api.imgbb.com/1/upload"
+ payload = {"key": IMGBB_API_KEY}
+ files = {"image": open(image_path, "rb")}
+ response = requests.post(url, data=payload, files=files)
+ result = response.json()
+ try:
+ return result['data']['display_url']
+ except Exception:
+ return None
+
+def reverse_serpapi(image_url, api_key):
+ params = {"engine": "google_reverse_image", "image_url": image_url, "api_key": api_key}
+ r = requests.get("https://serpapi.com/search", params=params)
+ return r.json()
+
+def reverse_zenserp(image_url, api_key, location=None, lang="fr"):
+ url = "https://app.zenserp.com/api/v2/search"
+ headers = {"apikey": api_key}
+ params = {"image_url": image_url, "hl": lang}
+ if location:
+ params["location"] = location
+ r = requests.get(url, params=params, headers=headers)
+ if r.status_code != 200:
+ return {"error": f"HTTP {r.status_code} : {r.text[:100]} ..."}
+ try:
+ return r.json()
+ except Exception:
+ return {"error": r.text[:300]}
+
+def get_opengraph_thumbnail(url):
+ try:
+ headers = {"User-Agent": "Mozilla/5.0"}
+ resp = requests.get(url, timeout=3, headers=headers)
+ soup = BeautifulSoup(resp.text, "html.parser")
+ og_image = soup.find("meta", property="og:image")
+ if og_image and og_image.get("content"):
+ return og_image["content"]
+ twitter_img = soup.find("meta", property="twitter:image")
+ if twitter_img and twitter_img.get("content"):
+ return twitter_img["content"]
+ parsed = requests.utils.urlparse(url)
+ base_url = f"{parsed.scheme}://{parsed.netloc}"
+ favicon_url = f"{base_url}/favicon.ico"
+ return favicon_url
+ except Exception:
+ return None
+
+def extract_direct_url(raw_url):
+ if raw_url and "google.com/url" in raw_url and "url=" in raw_url:
+ parsed = urllib.parse.urlparse(raw_url)
+ qs = urllib.parse.parse_qs(parsed.query)
+ actual_url = qs.get("url", [None])[0]
+ return actual_url if actual_url else raw_url
+ return raw_url
+
+st.header("FaceFinder OSINT | Recherche inversée multi-API (liens directs + miniatures)")
+
+img_file = st.file_uploader("Téléverse une image (jpg/png)", type=["jpg", "jpeg", "png"])
+img_url = None
+if img_file:
+ img = face_recognition.load_image_file(img_file)
+ faces = face_recognition.face_locations(img)
+ st.write(f"Nombre de visages détectés : {len(faces)}")
+ pil_img = Image.open(img_file)
+ draw = ImageDraw.Draw(pil_img)
+ for i, (top, right, bottom, left) in enumerate(faces):
+ draw.rectangle([left, top, right, bottom], outline="red", width=3)
+ draw.text((left, top-10), f"Visage {i+1}", fill="red")
+ st.image(pil_img, caption="Image annotée")
+ # Télécharger image annotée
+ output = io.BytesIO()
+ pil_img.save(output, format="PNG")
+ st.download_button("Télécharger l'image annotée", output.getvalue(), file_name="FaceFinderOSINT_annoted.png", mime="image/png")
+
+ # Sauvegarde temporaire et upload sur ImgBB
+ img_path = os.path.join(os.getcwd(), "face_to_search.jpg")
+ pil_img.save(img_path)
+ img_url = upload_image_imgbb(img_path)
+ if img_url:
+ st.success(f"Image hébergée : {img_url}")
+ st.image(img_url)
+ st.markdown(f"[Ouvrir l’image dans le navigateur]({img_url})")
+ else:
+ st.error("Échec de l’upload sur ImgBB.")
+
+if img_url:
+ st.markdown("## Lancer la recherche inversée")
+ location = st.text_input("Localisation (optionnel, ex: France, Paris)", value="")
+ lang = st.selectbox("Langue", ["fr", "en", "ar", "es", "de"], index=0)
+
+ for api in API_CONFIG:
+ used = API_CONFIG[api]["count"]
+ quota = API_CONFIG[api]["quota"]
+ st.write(f"{api} : {used}/{quota} requêtes utilisées")
+ btn = st.button(f"Recherche via {api}", key=api)
+ if btn:
+ if used < quota:
+ if api == "SerpApi":
+ result = reverse_serpapi(img_url, API_CONFIG[api]["api_key"])
+ if "image_results" in result:
+ st.write("### Principaux résultats SerpApi")
+ for res in result["image_results"][:5]:
+ link = extract_direct_url(res.get('link', ''))
+ thumb = res.get('thumbnail') or res.get('original')
+ if not thumb and link:
+ thumb = get_opengraph_thumbnail(link)
+ time.sleep(0.4)
+ if thumb:
+ st.image(thumb, width=100)
+ st.markdown(f"**{res.get('title','(Sans titre)')}**")
+ st.markdown(f"[Lien direct]({link})\n({res.get('displayed_link','')})")
+ st.write(f"_Source_: {res.get('source','')}")
+ if res.get('snippet'):
+ st.write(res['snippet'])
+ st.markdown("---")
+ else:
+ st.write("Aucun résultat d'image reconnu ou parsing impossible.")
+
+ elif api == "Zenserp":
+ result = reverse_zenserp(img_url, API_CONFIG[api]["api_key"], location=location or None, lang=lang)
+ if "error" in result:
+ st.error(f"Zenserp Error: {result['error']}")
+ else:
+ if "reverse_image_results" in result and "organic" in result["reverse_image_results"]:
+ st.write("### Principaux résultats Zenserp")
+ for res in result["reverse_image_results"]["organic"][:10]:
+ link = extract_direct_url(res.get('url', ''))
+ thumb = res.get('thumbnail') or res.get('image_url')
+ if not thumb and link:
+ thumb = get_opengraph_thumbnail(link)
+ time.sleep(0.4)
+ if thumb:
+ st.image(thumb, width=100)
+ st.markdown(f"**{res.get('title', '(Sans titre)')}**")
+ st.markdown(f"[Lien direct]({link})")
+ st.markdown("---")
+ else:
+ st.write("Aucun résultat d'image reconnu ou parsing impossible.")
+ API_CONFIG[api]["count"] += 1
+ save_counts()
+ else:
+ st.warning("Quota gratuit atteint pour cette API !")
+
+st.markdown("---")
+st.markdown("*Détection, annotation, hébergement sur ImgBB et recherche inversée automatisable sur toutes les APIs gratuites disponibles, avec miniatures et liens directs résolus !*")
diff --git a/pages/8_Domain_Intel.py b/pages/8_Domain_Intel.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc0a8397ffe2c52c5c0726ef69d544682d38d3f9
--- /dev/null
+++ b/pages/8_Domain_Intel.py
@@ -0,0 +1,303 @@
+"""
+Page Streamlit : Reconnaissance de Domaine
+Module OSINT pour Ba7ath Dashboard
+"""
+
+import streamlit as st
+import sys
+import os
+import pandas as pd
+import time
+
+# Ajouter le chemin des modules
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'spectre_modules'))
+
+try:
+ from domain_recon import run_recon
+except ImportError as e:
+ st.error(f"❌ Erreur d'import du module domain_recon : {e}")
+ st.stop()
+
+# Configuration de la page
+st.set_page_config(page_title="Domain Intel", page_icon="🗺️", layout="wide")
+
+# En-tête
+st.title("🗺️ Reconnaissance de Domaine")
+st.caption("WHOIS, DNS et sous-domaines - Sources publiques uniquement")
+
+# Avertissement légal
+with st.expander("⚖️ Mentions légales", expanded=False):
+ st.info("""
+ **Utilisation éthique uniquement**
+
+ Ce module collecte uniquement des informations publiques :
+ - Enregistrements WHOIS (base publique)
+ - Records DNS (résolution publique)
+ - Sous-domaines actifs (requêtes HTTP standard)
+
+ ⚠️ N'utilisez cet outil que sur des domaines dont vous avez l'autorisation
+ ou dans le cadre d'une investigation OSINT légitime.
+ """)
+
+# Formulaire de saisie
+st.markdown("---")
+
+col1, col2 = st.columns([3, 1])
+
+with col1:
+ domain_input = st.text_input(
+ "🔍 Domaine à investiguer",
+ placeholder="exemple.com (sans http:// ni www)",
+ help="Entrez uniquement le nom de domaine, sans protocole"
+ )
+
+with col2:
+ st.write("") # Espacement
+ st.write("") # Espacement
+ scan_subdomains = st.checkbox(
+ "Scanner les sous-domaines",
+ value=True,
+ help="⚠️ Peut prendre 1-3 minutes selon la taille de la wordlist"
+ )
+
+# Nettoyage de l'input
+if domain_input:
+ domain_input = domain_input.strip().lower()
+ domain_input = domain_input.replace('http://', '').replace('https://', '')
+ domain_input = domain_input.replace('www.', '')
+ domain_input = domain_input.split('/')[0] # Enlever les chemins
+
+# Bouton d'analyse
+analyze_btn = st.button("🚀 Lancer l'analyse", type="primary", use_container_width=True)
+
+# Exécution de l'analyse
+if analyze_btn:
+ if not domain_input:
+ st.error("⚠️ Veuillez entrer un nom de domaine")
+ else:
+ # Validation basique du format
+ if '.' not in domain_input or ' ' in domain_input:
+ st.error("⚠️ Format de domaine invalide")
+ else:
+ st.markdown("---")
+
+ # Barre de progression
+ progress_bar = st.progress(0, text="Initialisation...")
+
+ try:
+ # Lancement de la reconnaissance
+ progress_bar.progress(10, text="🔍 Récupération WHOIS...")
+
+ with st.spinner("Analyse en cours..."):
+ results = run_recon(domain_input, scan_subdomains=scan_subdomains)
+
+ progress_bar.progress(100, text="✅ Analyse terminée !")
+ progress_bar.empty()
+
+ # Affichage des résultats
+ st.success(f"✅ Analyse terminée pour **{domain_input}**")
+
+ # Organisation en onglets
+ tab1, tab2, tab3, tab4 = st.tabs([
+ "📋 WHOIS",
+ "🌐 DNS Records",
+ "🔗 Sous-domaines",
+ "📥 Export"
+ ])
+
+ # --- ONGLET WHOIS ---
+ with tab1:
+ st.subheader("Informations d'enregistrement")
+
+ whois_data = results.get('whois', {})
+
+ if 'error' in whois_data:
+ st.warning(f"⚠️ {whois_data['error']}")
+ elif whois_data:
+ # Extraire les infos clés
+ key_info = {}
+ for key in ['registrar', 'creation_date', 'expiration_date',
+ 'updated_date', 'status', 'name_servers']:
+ if key in whois_data:
+ key_info[key] = whois_data[key]
+
+ if key_info:
+ col_a, col_b = st.columns(2)
+
+ with col_a:
+ st.metric("📌 Registrar", key_info.get('registrar', 'N/A'))
+ st.metric("📅 Date de création", key_info.get('creation_date', 'N/A'))
+
+ with col_b:
+ st.metric("⏰ Expiration", key_info.get('expiration_date', 'N/A'))
+ st.metric("🔄 Dernière MAJ", key_info.get('updated_date', 'N/A'))
+
+ st.write("**Statut :**", key_info.get('status', 'N/A'))
+
+ if 'name_servers' in key_info:
+ st.write("**Serveurs de noms :**")
+ st.code(key_info['name_servers'])
+
+ # Affichage complet en expander
+ with st.expander("📄 Voir toutes les données WHOIS"):
+ st.json(whois_data)
+ else:
+ st.info("Aucune donnée WHOIS disponible")
+
+ # --- ONGLET DNS ---
+ with tab2:
+ st.subheader("Enregistrements DNS")
+
+ dns_data = results.get('dns', {})
+
+ if dns_data:
+ # Créer un DataFrame pour affichage
+ dns_rows = []
+ for record_type, records in dns_data.items():
+ if records:
+ for record in records:
+ dns_rows.append({
+ 'Type': record_type,
+ 'Valeur': record
+ })
+
+ if dns_rows:
+ dns_df = pd.DataFrame(dns_rows)
+
+ # Affichage avec style (CORRIGÉ)
+ st.dataframe(
+ dns_df,
+ width='stretch', # ← Correction ici
+ hide_index=True
+ )
+
+ # Statistiques
+ st.caption(f"📊 **{len(dns_rows)} enregistrements** trouvés sur **{len([t for t in dns_data if dns_data[t]])} types** différents")
+ else:
+ st.info("Aucun enregistrement DNS trouvé")
+ else:
+ st.warning("Impossible de récupérer les enregistrements DNS")
+
+ # --- ONGLET SOUS-DOMAINES ---
+ with tab3:
+ st.subheader("Sous-domaines actifs")
+
+ subdomains = results.get('subdomains', [])
+
+ if subdomains:
+ st.success(f"✅ **{len(subdomains)} sous-domaines** découverts")
+
+ # Affichage en colonnes
+ cols = st.columns(3)
+ for idx, subdomain in enumerate(subdomains):
+ with cols[idx % 3]:
+ st.text(f"🔗 {subdomain}")
+
+ # Liste complète en expander
+ with st.expander("📋 Liste complète (copiable)"):
+ st.code('\n'.join(subdomains))
+
+ elif scan_subdomains:
+ st.info("Aucun sous-domaine trouvé dans la wordlist")
+ else:
+ st.info("Scan de sous-domaines désactivé")
+
+ # --- ONGLET EXPORT (CORRIGÉ) ---
+ with tab4:
+ st.subheader("Exportation des données")
+
+ # Export CSV avec timestamp
+ export_data = []
+
+ # Métadonnées
+ export_data.append({
+ 'Catégorie': 'Métadonnées',
+ 'Type': 'Domaine',
+ 'Clé': 'domaine_cible',
+ 'Valeur': domain_input,
+ 'Timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ # WHOIS
+ for key, value in results.get('whois', {}).items():
+ export_data.append({
+ 'Catégorie': 'WHOIS',
+ 'Type': key,
+ 'Clé': key,
+ 'Valeur': value,
+ 'Timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ # DNS
+ for record_type, records in results.get('dns', {}).items():
+ for record in records:
+ export_data.append({
+ 'Catégorie': 'DNS',
+ 'Type': record_type,
+ 'Clé': record_type,
+ 'Valeur': record,
+ 'Timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ # Sous-domaines
+ for subdomain in results.get('subdomains', []):
+ export_data.append({
+ 'Catégorie': 'Sous-domaine',
+ 'Type': 'Actif',
+ 'Clé': 'subdomain',
+ 'Valeur': subdomain,
+ 'Timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ export_df = pd.DataFrame(export_data)
+
+ col_exp1, col_exp2 = st.columns(2)
+
+ with col_exp1:
+ st.download_button(
+ label="📥 Télécharger le rapport CSV",
+ data=export_df.to_csv(index=False, encoding='utf-8-sig').encode('utf-8-sig'),
+ file_name=f"domain_intel_{domain_input.replace('.', '_')}.csv",
+ mime="text/csv",
+ use_container_width=True
+ )
+
+ with col_exp2:
+ # Bouton pour le rapport CSV automatique (si généré)
+ if results.get('report_filename'):
+ report_path = os.path.join('reports', results['report_filename'])
+ if os.path.exists(report_path):
+ with open(report_path, 'rb') as f: # ← Mode binaire pour CSV
+ report_content = f.read()
+
+ st.download_button(
+ label="📄 Télécharger le rapport complet",
+ data=report_content,
+ file_name=results['report_filename'],
+ mime="text/csv", # ← CSV au lieu de text/plain
+ use_container_width=True
+ )
+
+ # Aperçu des données (CORRIGÉ)
+ with st.expander("👁️ Aperçu des données CSV"):
+ st.dataframe(export_df, width='stretch') # ← Correction ici
+
+ # Statistiques
+ st.caption(f"""
+ 📊 **Statistiques du rapport**
+ - Total d'entrées : {len(export_df)}
+ - WHOIS : {len(export_df[export_df['Catégorie'] == 'WHOIS'])} entrées
+ - DNS : {len(export_df[export_df['Catégorie'] == 'DNS'])} enregistrements
+ - Sous-domaines : {len(export_df[export_df['Catégorie'] == 'Sous-domaine'])} trouvés
+ """)
+
+ except Exception as e:
+ progress_bar.empty()
+ st.error(f"❌ Erreur lors de l'analyse : {str(e)}")
+
+ with st.expander("🐛 Détails de l'erreur (pour debug)"):
+ st.exception(e)
+
+# Pied de page
+st.markdown("---")
+st.caption("🕵️ Ba7ath OSINT Suite | Module de reconnaissance passive")
diff --git a/pages/9_SubdomainFinder.py b/pages/9_SubdomainFinder.py
new file mode 100644
index 0000000000000000000000000000000000000000..20940141d7a711c2e97b0f556762034282076e47
--- /dev/null
+++ b/pages/9_SubdomainFinder.py
@@ -0,0 +1,70 @@
+import streamlit as st
+
+st.set_page_config(page_title="Accès Restreint", page_icon="🔒", layout="centered")
+
+st.markdown("""
+
+
+
+
🛡️
+
Accès Restreint
+
+ Ce module avancé a été désactivé dans cette version afin d'optimiser les performances et d'alléger l'application finale.
+ Il requiert des ressources matérielles spécifiques ou des configurations environnementales complexes.
+
+
+ 🔒 Applications Réservées à Ba7ath Project Team
+
+
+""", unsafe_allow_html=True)
+
+st.stop()
diff --git a/reports/.gitkeep b/reports/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..776857c44b02b948033d2aa402fd11fdc0669488
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,16 @@
+streamlit
+python-dotenv
+requests
+pandas
+beautifulsoup4
+selenium
+folium
+streamlit-folium
+maigret
+TikTokApi
+python-whois
+plotly
+exifread
+face_recognition
+duckduckgo_search
+google-api-python-client
diff --git a/run_app.py b/run_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..93c078576b98c0cbd339e74b470ac1db761a417c
--- /dev/null
+++ b/run_app.py
@@ -0,0 +1,45 @@
+import os
+import sys
+import webbrowser
+import threading
+import time
+import multiprocessing
+import config
+
+# Charger les clés API dans l'environnement virtuel en toute sécurité
+config.load_keys()
+
+def start_streamlit():
+ # Import streamlit inside the function to ensure freeze_support is called first
+ import streamlit.web.cli as stcli
+
+ os.environ["STREAMLIT_SERVER_HEADLESS"] = "true"
+ os.environ["STREAMLIT_SERVER_PORT"] = "8501"
+ os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none"
+ os.environ["STREAMLIT_GLOBAL_DISABLE_WATCHDOG"] = "true"
+ os.environ["STREAMLIT_BROWSER_GATHER_USAGE_STATS"] = "false"
+
+ if getattr(sys, 'frozen', False):
+ base_dir = sys._MEIPASS
+ else:
+ base_dir = os.path.dirname(os.path.abspath(__file__))
+
+ dashboard_path = os.path.join(base_dir, 'dashboard.py')
+ sys.argv = ["streamlit", "run", dashboard_path, "--global.developmentMode=false"]
+
+ # Exécuter streamlit
+ sys.exit(stcli.main())
+
+def open_browser():
+ time.sleep(3) # Attendre 3 secondes que le serveur Streamlit démarre
+ webbrowser.open("http://localhost:8501")
+
+if __name__ == "__main__":
+ # Indispensable pour PyInstaller sur Windows avec certains packages (ex: playwright)
+ multiprocessing.freeze_support()
+
+ # Ouvrir le navigateur dans un thread séparé
+ threading.Thread(target=open_browser, daemon=True).start()
+
+ # Démarrer le serveur Streamlit
+ start_streamlit()
diff --git a/sherlock/.actor/Dockerfile b/sherlock/.actor/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f14d92b7fa451d6850d38961a70ab86c6ce9cf14
--- /dev/null
+++ b/sherlock/.actor/Dockerfile
@@ -0,0 +1,19 @@
+FROM sherlock/sherlock as sherlock
+
+# Install Node.js
+RUN apt-get update; apt-get install curl gpg -y
+RUN mkdir -p /etc/apt/keyrings
+RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
+RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
+RUN apt-get update && apt-get install -y curl bash git jq jo xz-utils nodejs
+
+# Install Apify CLI (node.js) for the Actor Runtime
+RUN npm -g install apify-cli
+
+# Install Dependencies for the Actor Shell Script
+RUN apt-get update && apt-get install -y bash jq jo xz-utils nodejs
+
+# Copy Actor dir with the actorization shell script
+COPY .actor/ .actor
+
+ENTRYPOINT [".actor/actor.sh"]
diff --git a/sherlock/.actor/README.md b/sherlock/.actor/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb42887f274c968ef62e2d9c50c2f217b16630f9
--- /dev/null
+++ b/sherlock/.actor/README.md
@@ -0,0 +1,93 @@
+# Sherlock Actor on Apify
+
+[](https://apify.com/netmilk/sherlock?fpr=sherlock)
+
+This Actor wraps the [Sherlock Project](https://sherlockproject.xyz/) to provide serverless username reconnaissance across social networks in the cloud. It helps you find usernames across multiple social media platforms without installing and running the tool locally.
+
+## What are Actors?
+[Actors](https://docs.apify.com/platform/actors?fpr=sherlock) are serverless microservices running on the [Apify Platform](https://apify.com/?fpr=sherlock). They are based on the [Actor SDK](https://docs.apify.com/sdk/js?fpr=sherlock) and can be found in the [Apify Store](https://apify.com/store?fpr=sherlock). Learn more about Actors in the [Apify Whitepaper](https://whitepaper.actor?fpr=sherlock).
+
+## Usage
+
+### Apify Console
+
+1. Go to the Apify Actor page
+2. Click "Run"
+3. In the input form, fill in **Username(s)** to search for
+4. The Actor will run and produce its outputs in the default datastore
+
+
+### Apify CLI
+
+```bash
+apify call YOUR_USERNAME/sherlock --input='{
+ "usernames": ["johndoe", "janedoe"]
+}'
+```
+
+### Using Apify API
+
+```bash
+curl --request POST \
+ --url "https://api.apify.com/v2/acts/YOUR_USERNAME~sherlock/run" \
+ --header 'Content-Type: application/json' \
+ --header 'Authorization: Bearer YOUR_API_TOKEN' \
+ --data '{
+ "usernames": ["johndoe", "janedoe"],
+ }
+}'
+```
+
+## Input Parameters
+
+The Actor accepts a JSON schema with the following structure:
+
+| Field | Type | Required | Default | Description |
+|-------|------|----------|---------|-------------|
+| `usernames` | array | Yes | - | List of usernames to search for |
+| `usernames[]` | string | Yes | "json" | Username to search for |
+
+
+### Example Input
+
+```json
+{
+ "usernames": ["techuser", "designuser"],
+}
+```
+
+## Output
+
+The Actor provides three types of outputs:
+
+### Dataset Record*
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| `username` | string | Yes | Username the search was conducted for |
+| `links` | array | Yes | Array with found links to the social media |
+| `links[]`| string | No | URL to the account
+
+### Example Dataset Item (JSON)
+
+```json
+{
+ "username": "johndoe",
+ "links": [
+ "https://github.com/johndoe"
+ ]
+}
+```
+
+## Performance & Resources
+
+- **Memory Requirements**:
+ - Minimum: 512 MB RAM
+ - Recommended: 1 GB RAM for multiple usernames
+- **Processing Time**:
+ - Single username: ~1-2 minutes
+ - Multiple usernames: 2-5 minutes
+ - Varies based on number of sites checked and response times
+
+
+For more help, check the [Sherlock Project documentation](https://github.com/sherlock-project/sherlock) or raise an issue in the Actor's repository.
diff --git a/sherlock/.actor/actor.sh b/sherlock/.actor/actor.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0f839b6990b0e2bd154de7e7de42fa8523742ef5
--- /dev/null
+++ b/sherlock/.actor/actor.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+INPUT=`apify actor:get-input | jq -r .usernames[] | xargs echo`
+echo "INPUT: $INPUT"
+
+sherlock $INPUT
+
+for username in $INPUT; do
+ # escape the special meaning leading characters
+ # https://github.com/jpmens/jo/blob/master/jo.md#description
+ safe_username=$(echo $username | sed 's/^@/\\@/' | sed 's/^:/\\:/' | sed 's/%/\\%/')
+ echo "pushing results for username: $username, content:"
+ cat $username.txt
+ sed '$d' $username.txt | jo -a | jo username=$safe_username links:=- | apify actor:push-data
+done
diff --git a/sherlock/.dockerignore b/sherlock/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..3d4950c663ddf9fe98f7b23dc9b9ba7266524399
--- /dev/null
+++ b/sherlock/.dockerignore
@@ -0,0 +1,8 @@
+.git/
+.vscode/
+screenshot/
+tests/
+*.txt
+!/requirements.txt
+venv/
+devel/
\ No newline at end of file
diff --git a/sherlock/.editorconfig b/sherlock/.editorconfig
new file mode 100644
index 0000000000000000000000000000000000000000..60fe1d3ad2e8aaf4d74c125cf90b8e87ac3904b7
--- /dev/null
+++ b/sherlock/.editorconfig
@@ -0,0 +1,18 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+curly_bracket_next_line = false
+spaces_around_operators = true
+
+[*.{markdown,md}]
+trim_trailing_whitespace = false
+
+[*.py]
+indent_size = 4
+quote_type = double
diff --git a/sherlock/.github/CODEOWNERS b/sherlock/.github/CODEOWNERS
new file mode 100644
index 0000000000000000000000000000000000000000..b2961bbd5e225434df9c262b010ebf08cf035994
--- /dev/null
+++ b/sherlock/.github/CODEOWNERS
@@ -0,0 +1,15 @@
+### REPOSITORY
+/.github/CODEOWNERS @sdushantha @ppfeister
+/.github/FUNDING.yml @sdushantha
+/LICENSE @sdushantha
+
+### PACKAGING
+# Changes made to these items without code owner approval may negatively
+# impact packaging pipelines.
+/pyproject.toml @ppfeister @sdushantha
+
+### REGRESSION
+/.github/workflows/regression.yml @ppfeister
+/tox.ini @ppfeister
+/pytest.ini @ppfeister
+/tests/ @ppfeister
diff --git a/sherlock/.github/FUNDING.yml b/sherlock/.github/FUNDING.yml
new file mode 100644
index 0000000000000000000000000000000000000000..52fb873755a948935369140ee4228b9140f8841c
--- /dev/null
+++ b/sherlock/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: [ sdushantha, ppfeister, matheusfelipeog ]
diff --git a/sherlock/.github/ISSUE_TEMPLATE/bug-report.yml b/sherlock/.github/ISSUE_TEMPLATE/bug-report.yml
new file mode 100644
index 0000000000000000000000000000000000000000..4229ca712cb8c576c0542d1a6dd78ca0937246ee
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -0,0 +1,71 @@
+name: Bug report
+description: File a bug report
+labels: ["bug"]
+body:
+ - type: dropdown
+ id: package
+ attributes:
+ label: Installation method
+ description: |
+ Some packages are maintained by the community, rather than by the Sherlock Project.
+ Knowing which packages are affected helps us diagnose package-specific bugs.
+ options:
+ - Select one
+ - PyPI (via pip)
+ - Homebrew
+ - Docker
+ - Kali repository (via apt)
+ - Built from source
+ - Other (indicate below)
+ validations:
+ required: true
+ - type: input
+ id: package-version
+ attributes:
+ label: Package version
+ description: |
+ Knowing the version of the package you are using can help us diagnose your issue more quickly.
+ You can find the version by running `sherlock --version`.
+ validations:
+ required: true
+ - type: textarea
+ id: description
+ attributes:
+ label: Description
+ description: |
+ Detailed descriptions that help contributors understand and reproduce your bug are much more likely to lead to a fix.
+ Please include the following information:
+ - What you were trying to do
+ - What you expected to happen
+ - What actually happened
+ placeholder: |
+ When doing {action}, the expected result should be {expected result}.
+ When doing {action}, however, the actual result was {actual result}.
+ This is undesirable because {reason}.
+ validations:
+ required: true
+ - type: textarea
+ id: steps-to-reproduce
+ attributes:
+ label: Steps to reproduce
+ description: Write a step by step list that will allow us to reproduce this bug.
+ placeholder: |
+ 1. Do something
+ 2. Then do something else
+ validations:
+ required: true
+ - type: textarea
+ id: additional-info
+ attributes:
+ label: Additional information
+ description: If you have some additional information, please write it here.
+ validations:
+ required: false
+ - type: checkboxes
+ id: terms
+ attributes:
+ label: Code of Conduct
+ description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/sherlock-project/sherlock/blob/master/docs/CODE_OF_CONDUCT.md).
+ options:
+ - label: I agree to follow this project's Code of Conduct
+ required: true
diff --git a/sherlock/.github/ISSUE_TEMPLATE/config.yml b/sherlock/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..ac2e8b47ddd5fba554da4139512c9a7e61592578
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1 @@
+blank_issues_enabled: false
diff --git a/sherlock/.github/ISSUE_TEMPLATE/false-negative.yml b/sherlock/.github/ISSUE_TEMPLATE/false-negative.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6dabc6e3431df42ed61f664c97c22d3f7b7fdb5e
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/false-negative.yml
@@ -0,0 +1,27 @@
+name: False negative
+description: Report a site that is returning false negative results
+title: "False negative for: "
+labels: ["false negative"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Please include the site name in the title of your issue.
+ Submit **one site per report** for faster resolution. If you have multiple sites in the same report, it often takes longer to fix.
+ - type: textarea
+ id: additional-info
+ attributes:
+ label: Additional info
+ description: If you know why the site is returning false negatives, or noticed any patterns, please explain.
+ placeholder: |
+ Reddit is returning false negatives because...
+ validations:
+ required: false
+ - type: checkboxes
+ id: terms
+ attributes:
+ label: Code of Conduct
+ description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/sherlock-project/sherlock/blob/master/docs/CODE_OF_CONDUCT.md).
+ options:
+ - label: I agree to follow this project's Code of Conduct
+ required: true
diff --git a/sherlock/.github/ISSUE_TEMPLATE/false-positive.yml b/sherlock/.github/ISSUE_TEMPLATE/false-positive.yml
new file mode 100644
index 0000000000000000000000000000000000000000..062b5d9b1fd00a36afb5f1206183451f27f94693
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/false-positive.yml
@@ -0,0 +1,28 @@
+name: False positive
+description: Report a site that is returning false positive results
+title: "False positive for: "
+labels: ["false positive"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Please include the site name in the title of your issue.
+ Submit **one site per report** for faster resolution. If you have multiple sites in the same report, it often takes longer to fix.
+ - type: textarea
+ id: additional-info
+ attributes:
+ label: Additional info
+ description: If you know why the site is returning false positives, or noticed any patterns, please explain.
+ placeholder: |
+ Reddit is returning false positives because...
+ False positives only occur after x searches...
+ validations:
+ required: false
+ - type: checkboxes
+ id: terms
+ attributes:
+ label: Code of Conduct
+ description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/sherlock-project/sherlock/blob/master/docs/CODE_OF_CONDUCT.md).
+ options:
+ - label: I agree to follow this project's Code of Conduct
+ required: true
diff --git a/sherlock/.github/ISSUE_TEMPLATE/feature-request.yml b/sherlock/.github/ISSUE_TEMPLATE/feature-request.yml
new file mode 100644
index 0000000000000000000000000000000000000000..97603c23e34c1767598a7afbec49f2bbdee4b95f
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/feature-request.yml
@@ -0,0 +1,24 @@
+name: Feature request
+description: Request a feature or enhancement
+labels: ["enhancement"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Concise and thoughtful titles help other contributors find and add your requested feature.
+ - type: textarea
+ id: description
+ attributes:
+ label: Description
+ description: Describe the feature you are requesting
+ placeholder: I'd like Sherlock to be able to do xyz
+ validations:
+ required: true
+ - type: checkboxes
+ id: terms
+ attributes:
+ label: Code of Conduct
+ description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/sherlock-project/sherlock/blob/master/docs/CODE_OF_CONDUCT.md).
+ options:
+ - label: I agree to follow this project's Code of Conduct
+ required: true
diff --git a/sherlock/.github/ISSUE_TEMPLATE/site-request.yml b/sherlock/.github/ISSUE_TEMPLATE/site-request.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5958fd27283ec026507337f97c65540d613fa084
--- /dev/null
+++ b/sherlock/.github/ISSUE_TEMPLATE/site-request.yml
@@ -0,0 +1,35 @@
+name: Reuest a new website
+description: Request that Sherlock add support for a new website
+title: "Requesting support for: "
+labels: ["site support request"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Ensure that the site name is in the title of your request. Requests without this information will be **closed**.
+ - type: input
+ id: site-url
+ attributes:
+ label: Site URL
+ description: |
+ What is the URL of the website indicated in your title?
+ Websites sometimes have similar names. This helps constributors find the correct site.
+ placeholder: https://reddit.com
+ validations:
+ required: true
+ - type: textarea
+ id: additional-info
+ attributes:
+ label: Additional info
+ description: If you have suggestions on how Sherlock should detect for usernames, please explain below
+ placeholder: Sherlock can detect if a username exists on Reddit by checking for...
+ validations:
+ required: false
+ - type: checkboxes
+ id: terms
+ attributes:
+ label: Code of Conduct
+ description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/sherlock-project/sherlock/blob/master/docs/CODE_OF_CONDUCT.md).
+ options:
+ - label: I agree to follow this project's Code of Conduct
+ required: true
diff --git a/sherlock/.github/SECURITY.md b/sherlock/.github/SECURITY.md
new file mode 100644
index 0000000000000000000000000000000000000000..d03c44c958960f5baad7a92a134f7578422d034c
--- /dev/null
+++ b/sherlock/.github/SECURITY.md
@@ -0,0 +1,11 @@
+## Security Policy
+
+### Supported Versions
+
+Sherlock is a forward looking project. Only the latest and most current version is supported.
+
+### Reporting a Vulnerability
+
+Security concerns can be submitted [__here__][report-url] without risk of exposing sensitive information. For issues that are low severity or unlikely to see exploitation, public issues are often acceptable.
+
+[report-url]: https://github.com/sherlock-project/sherlock/security/advisories/new
diff --git a/sherlock/.github/workflows/exclusions.yml b/sherlock/.github/workflows/exclusions.yml
new file mode 100644
index 0000000000000000000000000000000000000000..59655864f2d43903de6f73066f308267c1c9778d
--- /dev/null
+++ b/sherlock/.github/workflows/exclusions.yml
@@ -0,0 +1,89 @@
+name: Exclusions Updater
+
+on:
+ schedule:
+ #- cron: '0 5 * * 0' # Runs at 05:00 every Sunday
+ - cron: '0 5 * * *' # Runs at 05:00 every day
+ workflow_dispatch:
+
+jobs:
+ update-exclusions:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v5
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: '3.13'
+
+ - name: Install Poetry
+ uses: abatilo/actions-poetry@v4
+ with:
+ poetry-version: 'latest'
+
+ - name: Install dependencies
+ run: |
+ poetry install --no-interaction --with dev
+
+ - name: Run false positive tests
+ run: |
+ $(poetry env activate)
+ pytest -q --tb no -m validate_targets_fp -n 20 | tee fp_test_results.txt
+ deactivate
+
+ - name: Parse false positive detections by desired categories
+ run: |
+ grep -oP '(?<=test_false_pos\[)[^\]]+(?=\].*result was Claimed)' fp_test_results.txt \
+ | sort -u > false_positive_exclusions.txt
+ grep -oP '(?<=test_false_pos\[)[^\]]+(?=\].*result was WAF)' fp_test_results.txt \
+ | sort -u > waf_hits.txt
+
+ - name: Detect if exclusions list changed
+ id: detect_changes
+ run: |
+ git fetch origin exclusions || true
+
+ if git show origin/exclusions:false_positive_exclusions.txt >/dev/null 2>&1; then
+ # If the exclusions branch and file exist, compare
+ if git diff --quiet origin/exclusions -- false_positive_exclusions.txt; then
+ echo "exclusions_changed=false" >> "$GITHUB_OUTPUT"
+ else
+ echo "exclusions_changed=true" >> "$GITHUB_OUTPUT"
+ fi
+ else
+ # If the exclusions branch or file do not exist, treat as changed
+ echo "exclusions_changed=true" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Quantify and display results
+ run: |
+ FP_COUNT=$(wc -l < false_positive_exclusions.txt | xargs)
+ WAF_COUNT=$(wc -l < waf_hits.txt | xargs)
+ echo ">>> Found $FP_COUNT false positives and $WAF_COUNT WAF hits."
+ echo ">>> False positive exclusions:" && cat false_positive_exclusions.txt
+ echo ">>> WAF hits:" && cat waf_hits.txt
+
+ - name: Commit and push exclusions list
+ if: steps.detect_changes.outputs.exclusions_changed == 'true'
+ run: |
+ git config user.name "Paul Pfeister (automation)"
+ git config user.email "code@pfeister.dev"
+
+ mv false_positive_exclusions.txt false_positive_exclusions.txt.tmp
+
+ git add -f false_positive_exclusions.txt.tmp # -f required to override .gitignore
+ git stash push -m "stash false positive exclusion list" -- false_positive_exclusions.txt.tmp
+
+ git fetch origin exclusions || true # Allows creation of branch if deleted
+ git checkout -B exclusions origin/exclusions || (git checkout --orphan exclusions && git rm -rf .)
+
+ git stash pop || true
+
+ mv false_positive_exclusions.txt.tmp false_positive_exclusions.txt
+
+ git rm -f false_positive_exclusions.txt.tmp || true
+ git add false_positive_exclusions.txt
+ git commit -m "auto: update exclusions list" || echo "No changes to commit"
+ git push origin exclusions
diff --git a/sherlock/.github/workflows/regression.yml b/sherlock/.github/workflows/regression.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f3864e677ce84b88c91145fe0b870711e939ec09
--- /dev/null
+++ b/sherlock/.github/workflows/regression.yml
@@ -0,0 +1,92 @@
+name: Regression Testing
+
+on:
+ pull_request:
+ branches:
+ - master
+ - release/**
+ paths:
+ - '.github/workflows/regression.yml'
+ - '**/*.json'
+ - '**/*.py'
+ - '**/*.ini'
+ - '**/*.toml'
+ - 'Dockerfile'
+ push:
+ branches:
+ - master
+ - release/**
+ paths:
+ - '.github/workflows/regression.yml'
+ - '**/*.json'
+ - '**/*.py'
+ - '**/*.ini'
+ - '**/*.toml'
+ - 'Dockerfile'
+
+jobs:
+ tox-lint:
+ runs-on: ubuntu-latest
+ # Linting is ran through tox to ensure that the same linter
+ # is used by local runners
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up linting environment
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.x'
+ - name: Install tox and related dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install tox
+ - name: Run tox linting environment
+ run: tox -e lint
+ tox-matrix:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ # We want to know what specicic versions it fails on
+ fail-fast: false
+ matrix:
+ os: [
+ ubuntu-latest,
+ windows-latest,
+ macos-latest,
+ ]
+ python-version: [
+ '3.10',
+ '3.11',
+ '3.12',
+ '3.13',
+ ]
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up environment ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install tox and related dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install tox
+ pip install tox-gh-actions
+ - name: Run tox
+ run: tox
+ docker-build-test:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+ - name: Get version from pyproject.toml
+ id: get-version
+ run: |
+ VERSION=$(grep -m1 'version = ' pyproject.toml | cut -d'"' -f2)
+ echo "version=$VERSION" >> $GITHUB_OUTPUT
+ - name: Build Docker image
+ run: |
+ docker build \
+ --build-arg VERSION_TAG=${{ steps.get-version.outputs.version }} \
+ -t sherlock-test:latest .
+ - name: Test Docker image runs
+ run: docker run --rm sherlock-test:latest --version
diff --git a/sherlock/.github/workflows/update-site-list.yml b/sherlock/.github/workflows/update-site-list.yml
new file mode 100644
index 0000000000000000000000000000000000000000..3efff5478f1862fbfb0b5c6271c06ccb5f990c89
--- /dev/null
+++ b/sherlock/.github/workflows/update-site-list.yml
@@ -0,0 +1,46 @@
+name: Update Site List
+
+# Trigger the workflow when changes are pushed to the main branch
+# and the changes include the sherlock_project/resources/data.json file
+on:
+ push:
+ branches:
+ - master
+ paths:
+ - sherlock_project/resources/data.json
+
+jobs:
+ sync-json-data:
+ # Use the latest version of Ubuntu as the runner environment
+ runs-on: ubuntu-latest
+
+ steps:
+ # Check out the code at the specified pull request head commit
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ fetch-depth: 0
+
+ # Install Python 3
+ - name: Install Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.x'
+
+ # Execute the site_list.py Python script
+ - name: Execute site-list.py
+ run: python devel/site-list.py
+
+ - name: Pushes to another repository
+ uses: sdushantha/github-action-push-to-another-repository@main
+ env:
+ SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
+ API_TOKEN_GITHUB: ${{ secrets.API_TOKEN_GITHUB }}
+ with:
+ source-directory: 'output'
+ destination-github-username: 'sherlock-project'
+ commit-message: 'Updated site list'
+ destination-repository-name: 'sherlockproject.xyz'
+ user-email: siddharth.dushantha@gmail.com
+ target-branch: master
diff --git a/sherlock/.github/workflows/validate_modified_targets.yml b/sherlock/.github/workflows/validate_modified_targets.yml
new file mode 100644
index 0000000000000000000000000000000000000000..82ee020d9e35f60c35f68dc68b32015662ddd42f
--- /dev/null
+++ b/sherlock/.github/workflows/validate_modified_targets.yml
@@ -0,0 +1,126 @@
+name: Modified Target Validation
+
+on:
+ pull_request_target:
+ branches:
+ - master
+ paths:
+ - "sherlock_project/resources/data.json"
+
+jobs:
+ validate-modified-targets:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v5
+ with:
+ # Checkout the base branch but fetch all history to avoid a second fetch call
+ ref: ${{ github.base_ref }}
+ fetch-depth: 0
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.13"
+
+ - name: Install Poetry
+ uses: abatilo/actions-poetry@v4
+ with:
+ poetry-version: "latest"
+
+ - name: Install dependencies
+ run: |
+ poetry install --no-interaction --with dev
+
+ - name: Prepare JSON versions for comparison
+ run: |
+ # Fetch only the PR's branch head (single network call in this step)
+ git fetch origin pull/${{ github.event.pull_request.number }}/head:pr
+
+ # Find the merge-base commit between the target branch and the PR branch
+ MERGE_BASE=$(git merge-base origin/${{ github.base_ref }} pr)
+ echo "Comparing PR head against merge-base commit: $MERGE_BASE"
+
+ # Safely extract the file from the PR's head and the merge-base commit
+ git show pr:sherlock_project/resources/data.json > data.json.head
+ git show $MERGE_BASE:sherlock_project/resources/data.json > data.json.base
+
+ # CRITICAL FIX: Overwrite the checked-out data.json with the one from the PR
+ # This ensures that pytest runs against the new, updated file.
+ cp data.json.head sherlock_project/resources/data.json
+
+ - name: Discover modified targets
+ id: discover-modified
+ run: |
+ CHANGED=$(
+ python - <<'EOF'
+ import json
+ import sys
+ try:
+ with open("data.json.base") as f: base = json.load(f)
+ with open("data.json.head") as f: head = json.load(f)
+ except FileNotFoundError as e:
+ print(f"Error: Could not find {e.filename}", file=sys.stderr)
+ sys.exit(1)
+ except json.JSONDecodeError as e:
+ print(f"Error: Could not decode JSON from a file - {e}", file=sys.stderr)
+ sys.exit(1)
+
+ changed = []
+ for k, v in head.items():
+ if k not in base or base[k] != v:
+ changed.append(k)
+
+ print(",".join(sorted(changed)))
+ EOF
+ )
+
+ # Preserve changelist
+ echo -e ">>> Changed targets: \n$(echo $CHANGED | tr ',' '\n')"
+ echo "changed_targets=$CHANGED" >> "$GITHUB_OUTPUT"
+
+ - name: Validate remote manifest against local schema
+ if: steps.discover-modified.outputs.changed_targets != ''
+ run: |
+ poetry run pytest tests/test_manifest.py::test_validate_manifest_against_local_schema
+
+ # --- The rest of the steps below are unchanged ---
+
+ - name: Validate modified targets
+ if: steps.discover-modified.outputs.changed_targets != ''
+ continue-on-error: true
+ run: |
+ poetry run pytest -q --tb no -rA -m validate_targets -n 20 \
+ --chunked-sites "${{ steps.discover-modified.outputs.changed_targets }}" \
+ --junitxml=validation_results.xml
+
+ - name: Prepare validation summary
+ if: steps.discover-modified.outputs.changed_targets != ''
+ id: prepare-summary
+ run: |
+ summary=$(
+ poetry run python devel/summarize_site_validation.py validation_results.xml || echo "Failed to generate summary of test results"
+ )
+ echo "$summary" > validation_summary.md
+
+ - name: Announce validation results
+ if: steps.discover-modified.outputs.changed_targets != ''
+ uses: actions/github-script@v8
+ with:
+ script: |
+ const fs = require('fs');
+ const body = fs.readFileSync('validation_summary.md', 'utf8');
+ await github.rest.issues.createComment({
+ issue_number: context.payload.pull_request.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ body: body,
+ });
+
+ - name: This step shows as ran when no modifications are found
+ if: steps.discover-modified.outputs.changed_targets == ''
+ run: |
+ echo "No modified targets found"
diff --git a/sherlock/.gitignore b/sherlock/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..28e9ce3d568f8f06c7bff335b70d92ae8593b60d
--- /dev/null
+++ b/sherlock/.gitignore
@@ -0,0 +1,47 @@
+# Virtual Environments
+venv/
+bin/
+lib/
+pyvenv.cfg
+poetry.lock
+
+# Regression Testing
+.coverage
+.tox/
+
+# Editor Configurations
+.vscode/
+.idea/
+
+# Python
+__pycache__/
+
+# Pip
+src/
+
+# Devel, Build, and Installation
+*.egg-info/
+dist/**
+
+# Jupyter Notebook
+.ipynb_checkpoints
+*.ipynb
+
+# Output files, except requirements.txt
+*.txt
+!requirements.txt
+
+# Comma-Separated Values (CSV) Reports
+*.csv
+
+#XLSX Reports
+*.xlsx
+
+# Excluded sites list
+tests/.excluded_sites
+
+# MacOS Folder Metadata File
+.DS_Store
+
+# Vim swap files
+*.swp
diff --git a/sherlock/Dockerfile b/sherlock/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..64c40ad64e177951ec15fa5d171f79a4a11cf385
--- /dev/null
+++ b/sherlock/Dockerfile
@@ -0,0 +1,31 @@
+# Release instructions:
+ # 1. Update the version tag in the Dockerfile to match the version in sherlock/__init__.py
+ # 2. Update the VCS_REF tag to match the tagged version's FULL commit hash
+ # 3. Build image with BOTH latest and version tags
+ # i.e. `docker build -t sherlock/sherlock:0.16.0 -t sherlock/sherlock:latest .`
+
+FROM python:3.12-slim-bullseye AS build
+WORKDIR /sherlock
+
+RUN pip3 install --no-cache-dir --upgrade pip
+
+FROM python:3.12-slim-bullseye
+WORKDIR /sherlock
+
+ARG VCS_REF= # CHANGE ME ON UPDATE
+ARG VCS_URL="https://github.com/sherlock-project/sherlock"
+ARG VERSION_TAG= # CHANGE ME ON UPDATE
+
+ENV SHERLOCK_ENV=docker
+
+LABEL org.label-schema.vcs-ref=$VCS_REF \
+ org.label-schema.vcs-url=$VCS_URL \
+ org.label-schema.name="Sherlock" \
+ org.label-schema.version=$VERSION_TAG \
+ website="https://sherlockproject.xyz"
+
+RUN pip3 install --no-cache-dir sherlock-project==$VERSION_TAG
+
+WORKDIR /sherlock
+
+ENTRYPOINT ["sherlock"]
diff --git a/sherlock/LICENSE b/sherlock/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..df687dab83dab5f88b3c6d096562dcaa3af19eb8
--- /dev/null
+++ b/sherlock/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2019 Sherlock Project
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/sherlock/devel/site-list.py b/sherlock/devel/site-list.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a46d798239512fde70e7b5001f31133fbc2a7fe
--- /dev/null
+++ b/sherlock/devel/site-list.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+# This module generates the listing of supported sites which can be found in
+# sites.mdx. It also organizes all the sites in alphanumeric order
+import json
+import os
+
+DATA_REL_URI: str = "sherlock_project/resources/data.json"
+
+DEFAULT_ENCODING = "utf-8"
+
+# Read the data.json file
+with open(DATA_REL_URI, "r", encoding=DEFAULT_ENCODING) as data_file:
+ data: dict = json.load(data_file)
+
+# Removes schema-specific keywords for proper processing
+social_networks = data.copy()
+social_networks.pop('$schema', None)
+
+# Sort the social networks in alphanumeric order
+social_networks = sorted(social_networks.items())
+
+# Make output dir where the site list will be written
+os.mkdir("output")
+
+# Write the list of supported sites to sites.mdx
+with open("output/sites.mdx", "w", encoding=DEFAULT_ENCODING) as site_file:
+ site_file.write("---\n")
+ site_file.write("title: 'List of supported sites'\n")
+ site_file.write("sidebarTitle: 'Supported sites'\n")
+ site_file.write("icon: 'globe'\n")
+ site_file.write("description: 'Sherlock currently supports **400+** sites'\n")
+ site_file.write("---\n\n")
+
+ for social_network, info in social_networks:
+ url_main = info["urlMain"]
+ is_nsfw = "**(NSFW)**" if info.get("isNSFW") else ""
+ site_file.write(f"1. [{social_network}]({url_main}) {is_nsfw}\n")
+
+# Overwrite the data.json file with sorted data
+with open(DATA_REL_URI, "w", encoding=DEFAULT_ENCODING) as data_file:
+ sorted_data = json.dumps(data, indent=2, sort_keys=True)
+ data_file.write(sorted_data)
+ data_file.write("\n") # Keep the newline after writing data
+
+print("Finished updating supported site listing!")
diff --git a/sherlock/devel/summarize_site_validation.py b/sherlock/devel/summarize_site_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba542ff5d2e8acf3815c709dc9ffcadf29f1a7f9
--- /dev/null
+++ b/sherlock/devel/summarize_site_validation.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+# This module summarizes the results of site validation tests queued by
+# workflow validate_modified_targets for presentation in Issue comments.
+
+from defusedxml import ElementTree as ET
+import sys
+from pathlib import Path
+
+def summarize_junit_xml(xml_path: Path) -> str:
+ tree = ET.parse(xml_path)
+ root = tree.getroot()
+ suite = root.find('testsuite')
+
+ pass_message: str = ":heavy_check_mark: Pass"
+ fail_message: str = ":x: Fail"
+
+ if suite is None:
+ raise ValueError("Invalid JUnit XML: No testsuite found")
+
+ summary_lines: list[str] = []
+ summary_lines.append("#### Automatic validation of changes\n")
+ summary_lines.append("| Target | F+ Check | F- Check |")
+ summary_lines.append("|---|---|---|")
+
+ failures = int(suite.get('failures', 0))
+ errors_detected: bool = False
+
+ results: dict[str, dict[str, str]] = {}
+
+ for testcase in suite.findall('testcase'):
+ test_name = testcase.get('name').split('[')[0]
+ site_name = testcase.get('name').split('[')[1].rstrip(']')
+ failure = testcase.find('failure')
+ error = testcase.find('error')
+
+ if site_name not in results:
+ results[site_name] = {}
+
+ if test_name == "test_false_neg":
+ results[site_name]['F- Check'] = pass_message if failure is None and error is None else fail_message
+ elif test_name == "test_false_pos":
+ results[site_name]['F+ Check'] = pass_message if failure is None and error is None else fail_message
+
+ if error is not None:
+ errors_detected = True
+
+ for result in results:
+ summary_lines.append(f"| {result} | {results[result].get('F+ Check', 'Error!')} | {results[result].get('F- Check', 'Error!')} |")
+
+ if failures > 0:
+ summary_lines.append("\n___\n" +
+ "\nFailures were detected on at least one updated target. Commits containing accuracy failures" +
+ " will often not be merged (unless a rationale is provided, such as false negatives due to regional differences).")
+
+ if errors_detected:
+ summary_lines.append("\n___\n" +
+ "\n**Errors were detected during validation. Please review the workflow logs.**")
+
+ return "\n".join(summary_lines)
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("Usage: summarize_site_validation.py ")
+ sys.exit(1)
+
+ xml_path: Path = Path(sys.argv[1])
+ if not xml_path.is_file():
+ print(f"Error: File '{xml_path}' does not exist.")
+ sys.exit(1)
+
+ summary: str = summarize_junit_xml(xml_path)
+ print(summary)
diff --git a/sherlock/docs/CODE_OF_CONDUCT.md b/sherlock/docs/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..73eebed459b24ac0882c99177a94a6aab4b59057
--- /dev/null
+++ b/sherlock/docs/CODE_OF_CONDUCT.md
@@ -0,0 +1,130 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at yahya.arbabi@gmail.com.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
\ No newline at end of file
diff --git a/sherlock/docs/README.md b/sherlock/docs/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..227f55a0afad8152780bebfda54c0b41773db4a2
--- /dev/null
+++ b/sherlock/docs/README.md
@@ -0,0 +1,143 @@
+
+
+
+
+ Hunt down social media accounts by username across 400+ social networks
+
+
+
+
+ Installation
+ •
+ Usage
+ •
+ Contributing
+
+
+
+
+
+
+
+## Installation
+
+> [!WARNING]
+> Packages for ParrotOS and Ubuntu 24.04, maintained by a third party, appear to be __broken__.
+> Users of these systems should defer to pipx/pip or Docker.
+
+| Method | Notes |
+| - | - |
+| `pipx install sherlock-project` | `pip` may be used in place of `pipx` |
+| `docker run -it --rm sherlock/sherlock` |
+| `dnf install sherlock-project` | |
+
+Community-maintained packages are available for Debian (>= 13), Ubuntu (>= 22.10), Homebrew, Kali, and BlackArch. These packages are not directly supported or maintained by the Sherlock Project.
+
+See all alternative installation methods [here](https://sherlockproject.xyz/installation)
+
+## General usage
+
+To search for only one user:
+```bash
+sherlock user123
+```
+
+To search for more than one user:
+```bash
+sherlock user1 user2 user3
+```
+
+Accounts found will be stored in an individual text file with the corresponding username (e.g ```user123.txt```).
+
+```console
+$ sherlock --help
+usage: sherlock [-h] [--version] [--verbose] [--folderoutput FOLDEROUTPUT]
+ [--output OUTPUT] [--tor] [--unique-tor] [--csv] [--xlsx]
+ [--site SITE_NAME] [--proxy PROXY_URL] [--json JSON_FILE]
+ [--timeout TIMEOUT] [--print-all] [--print-found] [--no-color]
+ [--browse] [--local] [--nsfw]
+ USERNAMES [USERNAMES ...]
+
+Sherlock: Find Usernames Across Social Networks (Version 0.14.3)
+
+positional arguments:
+ USERNAMES One or more usernames to check with social networks.
+ Check similar usernames using {?} (replace to '_', '-', '.').
+
+optional arguments:
+ -h, --help show this help message and exit
+ --version Display version information and dependencies.
+ --verbose, -v, -d, --debug
+ Display extra debugging information and metrics.
+ --folderoutput FOLDEROUTPUT, -fo FOLDEROUTPUT
+ If using multiple usernames, the output of the results will be
+ saved to this folder.
+ --output OUTPUT, -o OUTPUT
+ If using single username, the output of the result will be saved
+ to this file.
+ --tor, -t Make requests over Tor; increases runtime; requires Tor to be
+ installed and in system path.
+ --unique-tor, -u Make requests over Tor with new Tor circuit after each request;
+ increases runtime; requires Tor to be installed and in system
+ path.
+ --csv Create Comma-Separated Values (CSV) File.
+ --xlsx Create the standard file for the modern Microsoft Excel
+ spreadsheet (xlsx).
+ --site SITE_NAME Limit analysis to just the listed sites. Add multiple options to
+ specify more than one site.
+ --proxy PROXY_URL, -p PROXY_URL
+ Make requests over a proxy. e.g. socks5://127.0.0.1:1080
+ --json JSON_FILE, -j JSON_FILE
+ Load data from a JSON file or an online, valid, JSON file.
+ --timeout TIMEOUT Time (in seconds) to wait for response to requests (Default: 60)
+ --print-all Output sites where the username was not found.
+ --print-found Output sites where the username was found.
+ --no-color Don't color terminal output
+ --browse, -b Browse to all results on default browser.
+ --local, -l Force the use of the local data.json file.
+ --nsfw Include checking of NSFW sites from default list.
+```
+## Apify Actor Usage [](https://apify.com/netmilk/sherlock?fpr=sherlock)
+
+
+
+You can run Sherlock in the cloud without installation using the [Sherlock Actor](https://apify.com/netmilk/sherlock?fpr=sherlock) on [Apify](https://apify.com?fpr=sherlock) free of charge.
+
+``` bash
+$ echo '{"usernames":["user123"]}' | apify call -so netmilk/sherlock
+[{
+ "username": "user123",
+ "links": [
+ "https://www.1337x.to/user/user123/",
+ ...
+ ]
+}]
+```
+
+Read more about the [Sherlock Actor](../.actor/README.md), including how to use it programmatically via the Apify [API](https://apify.com/netmilk/sherlock/api?fpr=sherlock), [CLI](https://docs.apify.com/cli/?fpr=sherlock) and [JS/TS and Python SDKs](https://docs.apify.com/sdk?fpr=sherlock).
+
+## Credits
+
+Thank you to everyone who has contributed to Sherlock! ❤️
+
+
+
+
+
+## Star History
+
+
+
+
+
+
+
+## License
+
+MIT © Sherlock Project
+Original Creator - [Siddharth Dushantha](https://github.com/sdushantha)
+
+
+
+[ext_pypi]: https://pypi.org/project/sherlock-project/
+[ext_brew]: https://formulae.brew.sh/formula/sherlock
diff --git a/sherlock/docs/pyproject/README.md b/sherlock/docs/pyproject/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..31522e57800e867f853f18235c083191863bf06b
--- /dev/null
+++ b/sherlock/docs/pyproject/README.md
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+ Hunt down social media accounts by username across 400+ social networks
+
+ Additional documentation can be found at our GitHub repository
+
+
+
+## Usage
+
+```console
+$ sherlock --help
+usage: sherlock [-h] [--version] [--verbose] [--folderoutput FOLDEROUTPUT]
+ [--output OUTPUT] [--tor] [--unique-tor] [--csv] [--xlsx]
+ [--site SITE_NAME] [--proxy PROXY_URL] [--json JSON_FILE]
+ [--timeout TIMEOUT] [--print-all] [--print-found] [--no-color]
+ [--browse] [--local] [--nsfw]
+ USERNAMES [USERNAMES ...]
+```
+
+To search for only one user:
+```bash
+$ sherlock user123
+```
+
+To search for more than one user:
+```bash
+$ sherlock user1 user2 user3
+```
+
+
+___
+
+
+
+
+
+
diff --git a/sherlock/docs/removed-sites.md b/sherlock/docs/removed-sites.md
new file mode 100644
index 0000000000000000000000000000000000000000..345cf4ab6869a2f26c84ee67d18fbbb7f1f86021
--- /dev/null
+++ b/sherlock/docs/removed-sites.md
@@ -0,0 +1,1997 @@
+# List Of Sites Removed From Sherlock
+
+This is a list of sites implemented in such a way that the current design of
+Sherlock is not capable of determining if a given username exists or not.
+They are listed here in the hope that things may change in the future
+so they may be re-included.
+
+
+## gpodder.net
+
+As of 2020-05-25, all usernames are reported as available.
+
+The server is returning a HTTP Status 500 (Internal server error)
+for all queries.
+
+```json
+ "gpodder.net": {
+ "errorType": "status_code",
+ "rank": 2013984,
+ "url": "https://gpodder.net/user/{}",
+ "urlMain": "https://gpodder.net/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## Investing.com
+
+As of 2020-05-25, all usernames are reported as claimed.
+
+Any query against a user seems to be redirecting to a general
+information page at https://www.investing.com/brokers/. Probably
+required login before access.
+
+```json
+ "Investing.com": {
+ "errorType": "status_code",
+ "rank": 196,
+ "url": "https://www.investing.com/traders/{}",
+ "urlMain": "https://www.investing.com/",
+ "username_claimed": "jenny",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## AdobeForums
+
+As of 2020-04-12, all usernames are reported as available.
+
+When I went to the site to see what was going on, usernames that I know
+existed were redirecting to the main page.
+
+I was able to see user profiles without logging in, but the URL was not
+related to their user name. For example, user "tomke" went to
+https://community.adobe.com/t5/user/viewprofilepage/user-id/10882613.
+This can be detected, but it requires a different detection method.
+
+```json
+ "AdobeForums": {
+ "errorType": "status_code",
+ "rank": 59,
+ "url": "https://forums.adobe.com/people/{}",
+ "urlMain": "https://forums.adobe.com/",
+ "username_claimed": "jack",
+ "username_unclaimed": "noonewouldeverusethis77777"
+ },
+```
+
+## Basecamp
+
+As of 2020-02-23, all usernames are reported as not existing.
+
+
+```json
+ "Basecamp": {
+ "errorMsg": "The account you were looking for doesn't exist",
+ "errorType": "message",
+ "rank": 4914,
+ "url": "https://{}.basecamphq.com",
+ "urlMain": "https://basecamp.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Canva
+
+As of 2020-02-23, all usernames are reported as not existing.
+
+```json
+ "Canva": {
+ "errorType": "response_url",
+ "errorUrl": "https://www.canva.com/{}",
+ "rank": 128,
+ "url": "https://www.canva.com/{}",
+ "urlMain": "https://www.canva.com/",
+ "username_claimed": "jenny",
+ "username_unclaimed": "xgtrq"
+ },
+```
+
+## Pixabay
+
+As of 2020-01-21, all usernames are reported as not existing.
+
+```json
+ "Pixabay": {
+ "errorType": "status_code",
+ "rank": 378,
+ "url": "https://pixabay.com/en/users/{}",
+ "urlMain": "https://pixabay.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## NPM-Packages
+
+NPM-Packages are not users.
+
+```json
+ "NPM-Package": {
+ "errorType": "status_code",
+ "url": "https://www.npmjs.com/package/{}",
+ "urlMain": "https://www.npmjs.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Pexels
+
+As of 2020-01-21, all usernames are reported as not existing.
+
+```json
+ "Pexels": {
+ "errorType": "status_code",
+ "rank": 745,
+ "url": "https://www.pexels.com/@{}",
+ "urlMain": "https://www.pexels.com/",
+ "username_claimed": "bruno",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## RamblerDating
+
+As of 2019-12-31, site always times out.
+
+```json
+ "RamblerDating": {
+ "errorType": "response_url",
+ "errorUrl": "https://dating.rambler.ru/page/{}",
+ "rank": 322,
+ "url": "https://dating.rambler.ru/page/{}",
+ "urlMain": "https://dating.rambler.ru/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## YandexMarket
+
+As of 2019-12-31, all usernames are reported as existing.
+
+```json
+ "YandexMarket": {
+ "errorMsg": "\u0422\u0443\u0442 \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435\u0442",
+ "errorType": "message",
+ "rank": 47,
+ "url": "https://market.yandex.ru/user/{}/achievements",
+ "urlMain": "https://market.yandex.ru/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Codementor
+
+As of 2019-12-31, usernames that exist are not detected.
+
+```json
+ "Codementor": {
+ "errorType": "status_code",
+ "rank": 10252,
+ "url": "https://www.codementor.io/@{}",
+ "urlMain": "https://www.codementor.io/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## KiwiFarms
+
+As of 2019-12-31, the site gives a 403 for all usernames. You have to
+be logged into see a profile.
+
+```json
+ "KiwiFarms": {
+ "errorMsg": "The specified member cannot be found",
+ "errorType": "message",
+ "rank": 38737,
+ "url": "https://kiwifarms.net/members/?username={}",
+ "urlMain": "https://kiwifarms.net/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## Teknik
+
+As of 2019-11-30, the site causes Sherlock to just hang.
+
+```json
+ "Teknik": {
+ "errorMsg": "The user does not exist",
+ "errorType": "message",
+ "rank": 357163,
+ "url": "https://user.teknik.io/{}",
+ "urlMain": "https://teknik.io/",
+ "username_claimed": "red",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Shockwave
+
+As of 2019-11-28, usernames that exist give a 503 "Service Unavailable"
+HTTP Status.
+
+```json
+ "Shockwave": {
+ "errorMsg": "Oh no! You just finished all of the games on the internet!",
+ "errorType": "message",
+ "rank": 35916,
+ "url": "http://www.shockwave.com/member/profiles/{}.jsp",
+ "urlMain": "http://www.shockwave.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## Foursquare
+
+When usage of automated tool is detected. Whole IP is banned from future requests.
+There is an error message:
+
+> Please verify you are a human
+> Access to this page has been denied because we believe you are using automation tools to browse the website.
+
+```json
+ "Foursquare": {
+ "errorType": "status_code",
+ "rank": 1843,
+ "url": "https://foursquare.com/{}",
+ "urlMain": "https://foursquare.com/",
+ "username_claimed": "dens",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Khan Academy
+
+Usernames that don't exist are detected. First noticed 2019-10-25.
+
+```json
+ "Khan Academy": {
+ "errorType": "status_code",
+ "rank": 377,
+ "url": "https://www.khanacademy.org/profile/{}",
+ "urlMain": "https://www.khanacademy.org/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## EVE Online
+
+Usernames that exist are not detected.
+
+```json
+ "EVE Online": {
+ "errorType": "response_url",
+ "errorUrl": "https://eveonline.com",
+ "rank": 15347,
+ "url": "https://evewho.com/pilot/{}/",
+ "urlMain": "https://eveonline.com",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## AngelList
+
+Usernames that exist are not detected. Forbidden Request 403 Error.
+
+```json
+ "AngelList": {
+ "errorType": "status_code",
+ "rank": 5767,
+ "url": "https://angel.co/u/{}",
+ "urlMain": "https://angel.co/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## PowerShell Gallery
+
+Accidentally merged even though the original pull request showed that all
+user names were available.
+
+```json
+ "PowerShell Gallery": {
+ "errorType": "status_code",
+ "rank": 163562,
+ "url": "https://www.powershellgallery.com/profiles/{}",
+ "urlMain": "https://www.powershellgallery.com",
+ "username_claimed": "powershellteam",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## StreamMe
+
+On 2019-04-07, I get a Timed Out message from the website. It has not
+been working earlier either (for some weeks). It takes about 21s before
+the site finally times out, so it really makes getting the results from
+Sherlock a pain.
+
+If the site becomes available in the future, we can put it back in.
+
+```json
+ "StreamMe": {
+ "errorType": "status_code",
+ "rank": 31702,
+ "url": "https://www.stream.me/{}",
+ "urlMain": "https://www.stream.me/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## BlackPlanet
+
+This site has always returned a false positive. The site returns the exact
+same text for a claimed or an unclaimed username. The site must be rendering
+all of the different content using Javascript in the browser. So, there is
+no way distinguish between the results with the current design of Sherlock.
+
+```json
+ "BlackPlanet": {
+ "errorMsg": "My Hits",
+ "errorType": "message",
+ "rank": 110021,
+ "url": "http://blackplanet.com/{}",
+ "urlMain": "http://blackplanet.com/"
+ },
+```
+
+## Fotolog
+
+Around 2019-02-09, I get a 502 HTTP error (bad gateway) for any access. On
+2019-03-10, the site is up, but it is in maintenance mode.
+
+It does not seem to be working, so there is no sense in including it in
+Sherlock.
+
+```json
+ "Fotolog": {
+ "errorType": "status_code",
+ "rank": 47777,
+ "url": "https://fotolog.com/{}",
+ "urlMain": "https://fotolog.com/"
+ },
+```
+
+## Google Plus
+
+On 2019-04-02, Google shutdown Google Plus. While the content for some
+users is available after that point, it is going away. And, no one will
+be able to create a new account. So, there is no value is keeping it in
+Sherlock.
+
+Good-bye [Google Plus](https://en.wikipedia.org/wiki/Google%2B)...
+
+```json
+ "Google Plus": {
+ "errorType": "status_code",
+ "rank": 1,
+ "url": "https://plus.google.com/+{}",
+ "urlMain": "https://plus.google.com/",
+ "username_claimed": "davidbrin1",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## InsaneJournal
+
+As of 2020-02-23, InsaneJournal returns false positive, when providing a username which contains a period.
+Since we were not able to find the criteria for a valid username, the best thing to do now is to remove it.
+
+```json
+ "InsaneJournal": {
+ "errorMsg": "Unknown user",
+ "errorType": "message",
+ "rank": 29728,
+ "url": "http://{}.insanejournal.com/profile",
+ "urlMain": "insanejournal.com",
+ "username_claimed": "blue",
+ "username_unclaimed": "dlyr6cd"
+ },
+```
+
+## Sports Tracker
+
+As of 2020-04-02, Sports Tracker returns false positives. Checking with `errorMsg` and `response_url`
+did not seem to work.
+
+```
+ "SportsTracker": {
+ "errorUrl": "https://www.sports-tracker.com/page-not-found",
+ "errorType": "response_url",
+ "rank": 93950,
+ "url": "https://www.sports-tracker.com/view_profile/{}",
+ "urlMain": "https://www.sports-tracker.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeveruse"
+ },
+```
+
+## Trip
+
+As of 2020-04-02, Trip by Skyscanner seems to not work beceause it keeps on
+redirecting to skyscanner.com whether the username exists or not.
+
+```json
+ "Trip": {
+ "errorType": "status_code",
+ "rank": 2847,
+ "url": "https://www.trip.skyscanner.com/user/{}",
+ "urlMain": "https://www.trip.skyscanner.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+
+```
+
+## boingboing.net
+
+As of 2020-04-02, boingboing.net requires a login to check if a user exits or not.
+
+```
+ "boingboing.net": {
+ "errorType": "status_code",
+ "rank": 5821,
+ "url": "https://bbs.boingboing.net/u/{}",
+ "urlMain": "https://boingboing.net/",
+ "username_claimed": "admin",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## elwoRU
+As of 2020-04-04, elwoRu does not exist anymore. I confirmed using
+downforeveryoneorjustme.com that the website is down.
+
+```json
+ "elwoRU": {
+ "errorMsg": "\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d",
+ "errorType": "message",
+ "rank": 254810,
+ "url": "https://elwo.ru/index/8-0-{}",
+ "urlMain": "https://elwo.ru/",
+ "username_claimed": "red",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## ingvarr.net.ru
+
+As of 2020-04-04, ingvarr.net.ru does not exist anymore. I confirmed using
+downforeveryoneorjustme.com that the website is down.
+
+```json
+ "ingvarr.net.ru": {
+ "errorMsg": "\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d",
+ "errorType": "message",
+ "rank": 107721,
+ "url": "http://ingvarr.net.ru/index/8-0-{}",
+ "urlMain": "http://ingvarr.net.ru/",
+ "username_claimed": "red",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Redsun.tf
+
+As of 2020-06-20, Redsun.tf seems to be adding random digits to the end of the usernames which makes it pretty much impossible
+for Sherlock to check for usernames on this particular website.
+
+```json
+ "Redsun.tf": {
+ "errorMsg": "The specified member cannot be found",
+ "errorType": "message",
+ "rank": 3796657,
+ "url": "https://forum.redsun.tf/members/?username={}",
+ "urlMain": "https://redsun.tf/",
+ "username_claimed": "dan",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## Creative Market
+
+As of 2020-06-20, Creative Market has a captcha to prove that you are a human, and because of this
+Sherlock is unable to check for username on this site because we will always get a page which asks
+us to prove that we are not a robot.
+
+```json
+ "CreativeMarket": {
+ "errorType": "status_code",
+ "rank": 1896,
+ "url": "https://creativemarket.com/users/{}",
+ "urlMain": "https://creativemarket.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## pvpru
+
+As of 2020-06-20, pvpru uses CloudFlair, and because of this we get a "Access denied" error whenever
+we try to check for a username.
+
+```json
+ "pvpru": {
+ "errorType": "status_code",
+ "rank": 405547,
+ "url": "https://pvpru.com/board/member.php?username={}&tab=aboutme#aboutme",
+ "urlMain": "https://pvpru.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## easyen
+As of 2020-06-21, easyen returns false positives when using a username which contains
+a period. Since we could not find the criteria for the usernames for this site, it will be
+removed
+
+```json
+ "easyen": {
+ "errorMsg": "\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d",
+ "errorType": "message",
+ "rank": 11564,
+ "url": "https://easyen.ru/index/8-0-{}",
+ "urlMain": "https://easyen.ru/",
+ "username_claimed": "wd",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## pedsovet
+As of 2020-06-21, pedsovet returns false positives when using a username which contains
+a period. Since we could not find the criteria for the usernames for this site, it will be
+removed
+
+```json
+ "pedsovet": {
+ "errorMsg": "\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d",
+ "errorType": "message",
+ "rank": 6776,
+ "url": "http://pedsovet.su/index/8-0-{}",
+ "urlMain": "http://pedsovet.su/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## radioskot
+As of 2020-06-21, radioskot returns false positives when using a username which contains
+a period. Since we could not find the criteria for the usernames for this site, it will be
+removed
+```json
+ "radioskot": {
+ "errorMsg": "\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d",
+ "errorType": "message",
+ "rank": 105878,
+ "url": "https://radioskot.ru/index/8-0-{}",
+ "urlMain": "https://radioskot.ru/",
+ "username_claimed": "red",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+
+## Coderwall
+As of 2020-07-06, Coderwall returns false positives when checking for an username which contains a period.
+I have tried to find out what Coderwall's criteria is for a valid username, but unfortunately I have not been able to
+find it and because of this, the best thing we can do now is to remove it.
+```json
+ "Coderwall": {
+ "errorMsg": "404! Our feels when that url is used",
+ "errorType": "message",
+ "rank": 11256,
+ "url": "https://coderwall.com/{}",
+ "urlMain": "https://coderwall.com/",
+ "username_claimed": "jenny",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+
+## TamTam
+As of 2020-07-06, TamTam returns false positives when given a username which contains a period
+```json
+ "TamTam": {
+ "errorType": "response_url",
+ "errorUrl": "https://tamtam.chat/",
+ "rank": 87903,
+ "url": "https://tamtam.chat/{}",
+ "urlMain": "https://tamtam.chat/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Zomato
+As of 2020-07-24, Zomato seems to be unstable. Majority of the time, Zomato takes a very long time to respond.
+```json
+ "Zomato": {
+ "errorType": "status_code",
+ "headers": {
+ "Accept-Language": "en-US,en;q=0.9"
+ },
+ "rank": 1920,
+ "url": "https://www.zomato.com/pl/{}/foodjourney",
+ "urlMain": "https://www.zomato.com/",
+ "username_claimed": "deepigoyal",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Mixer
+As of 2020-07-22, the Mixer service has closed down.
+```json
+ "mixer.com": {
+ "errorType": "status_code",
+ "rank": 1544,
+ "url": "https://mixer.com/{}",
+ "urlMain": "https://mixer.com/",
+ "urlProbe": "https://mixer.com/api/v1/channels/{}",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## KanoWorld
+As of 2020-07-22, KanoWorld's api.kano.me subdomain no longer exists which makes it not possible for us check for usernames.
+If an alternative way to check for usernames is found then it will added.
+```json
+ "KanoWorld": {
+ "errorType": "status_code",
+ "rank": 181933,
+ "url": "https://api.kano.me/progress/user/{}",
+ "urlMain": "https://world.kano.me/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## YandexCollection
+As of 2020-08-11, YandexCollection presents us with a recaptcha which prevents us from checking for usernames
+```json
+ "YandexCollection": {
+ "errorType": "status_code",
+ "url": "https://yandex.ru/collections/user/{}/",
+ "urlMain": "https://yandex.ru/collections/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## PayPal
+
+As of 2020-08-24, PayPal now returns false positives, which was found when running the tests, but will most likley be added again in the near
+future once we find a better error detecting method.
+```json
+ "PayPal": {
+ "errorMsg": " ",
+ "errorType": "message",
+ "url": "https://www.paypal.com/paypalme/{}",
+ "headers": {
+ "User-Agent": ""
+ },
+ "urlMain": "https://www.paypal.me/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noneownsthisusername7"
+ },
+```
+
+## ImageShack
+
+As of 2020-08-24, ImageShack now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a better error detecting method.
+```json
+ "ImageShack": {
+ "errorType": "response_url",
+ "errorUrl": "https://imageshack.us/",
+ "url": "https://imageshack.us/user/{}",
+ "urlMain": "https://imageshack.us/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Aptoide
+
+As of 2020-08-24, Aptoide now returns false positives, which was found when running the tests, but will most likley be added again in the near
+future once we find a better error detecting method.
+```json
+ "Aptoide": {
+ "errorType": "status_code",
+ "url": "https://{}.en.aptoide.com/",
+ "urlMain": "https://en.aptoide.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Crunchyroll
+
+As of 2020-08-24, Crunchyroll now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a better error detecting method.
+
+```json
+ "Crunchyroll": {
+ "errorType": "status_code",
+ "url": "https://www.crunchyroll.com/user/{}",
+ "urlMain": "https://www.crunchyroll.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## T-MobileSupport
+As of 2020-08-24, T-MobileSupport now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a better error detecting method.
+
+```json
+ "T-MobileSupport": {
+ "errorType": "status_code",
+ "url": "https://support.t-mobile.com/people/{}",
+ "urlMain": "https://support.t-mobile.com",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## OpenCollective
+
+As of 2020-08-24, OpenCollective now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a better error detecting method.
+
+```json
+ "OpenCollective": {
+ "errorType": "status_code",
+ "url": "https://opencollective.com/{}",
+ "urlMain": "https://opencollective.com/",
+ "username_claimed": "sindresorhus",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## SegmentFault
+
+As of 2020-08-24, SegmentFault now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a better error detecting method.
+
+```json
+ "SegmentFault": {
+ "errorType": "status_code",
+ "url": "https://segmentfault.com/u/{}",
+ "urlMain": "https://segmentfault.com/",
+ "username_claimed": "bule",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Viadeo
+
+As of 2020-08-24, Viadeo now returns false positives, which was found when running the tests, but will most likley be added again in the near future once we find a fix for this
+
+```json
+ "Viadeo": {
+ "errorType": "status_code",
+ "url": "http://fr.viadeo.com/en/profile/{}",
+ "urlMain": "http://fr.viadeo.com/en/",
+ "username_claimed": "franck.patissier",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## MeetMe
+
+As of 2020-09-02, MeetMe returns false positives
+
+```json
+ "MeetMe": {
+ "errorType": "response_url",
+ "errorUrl": "https://www.meetme.com/",
+ "url": "https://www.meetme.com/{}",
+ "urlMain": "https://www.meetme.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Linkdedin
+
+As of 2020-09-23, Linkedin returns false positives because we are prompted with prompted to login when checking for a user
+
+```json
+ "Linkedin": {
+ "errorMsg": "could not be found",
+ "errorType": "message",
+ "rank": 0,
+ "url": "https://www.linkedin.com/in/{}",
+ "urlMain": "https://www.linkedin.com/",
+ "username_claimed": "alex",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## tracr.co
+As of 2020-09-23, tracr.co returns false positives because the site seems to be shut down.
+```json
+ "tracr.co": {
+ "errorMsg": "No search results",
+ "errorType": "message",
+ "regexCheck": "^[A-Za-z0-9]{2,32}$",
+ "url": "https://tracr.co/users/1/{}",
+ "urlMain": "https://tracr.co/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Taringa
+
+As of 2020-09-23, Taringa returns false positives.
+
+```json
+ "Taringa": {
+ "errorType": "status_code",
+ "regexCheck": "^[^.]*$",
+ "url": "https://www.taringa.net/{}",
+ "urlMain": "https://taringa.net/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Photobucket
+As of 2020-10-21, Photobucket return false positives. This was reported in #785.
+```json
+ "Photobucket": {
+ "errorType": "status_code",
+ "url": "https://photobucket.com/user/{}/library",
+ "urlMain": "https://photobucket.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## 4PDA
+As of 2020-10-21, 4PDA returns false positives. This was reported in #784.
+
+```json
+ "4pda": {
+ "errorMsg": "[1,false,0]",
+ "errorType": "message",
+ "url": "https://4pda.ru/forum/index.php?act=search&source=pst&noform=1&username={}",
+ "urlMain": "https://4pda.ru/",
+ "urlProbe": " https://4pda.ru/forum/index.php?act=auth&action=chkname&login={}",
+ "username_claimed": "green",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## PokerStrategy
+As of 2020-10-21, PokerStrategy returns false positives. This was reported in #776.
+```json
+ "PokerStrategy": {
+ "errorType": "status_code",
+ "url": "http://www.pokerstrategy.net/user/{}/profile/",
+ "urlMain": "http://www.pokerstrategy.net",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Filmogs
+
+Filmogs has closed down.
+
+> **Filmogs is closed**
+> **31-Aug 2020** - We are preparing the last data export and collection of images. It will be published here by 19-Oct 2020. If you have requested an export of your data it will also be emailed to you by 19-Oct 2020.
+
+```json
+ "Filmogs": {
+ "errorType": "status_code",
+ "url": "https://www.filmo.gs/users/{}",
+ "urlMain": "https://www.filmo.gs/",
+ "username_claimed": "cupparober",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## 500px
+As of 2021-01-13, 500px returns false positives. This will hopefully be fixed soon once we add the ability to add different
+request methods.
+
+```json
+ "500px": {
+ "errorMsg": "No message available",
+ "errorType": "message",
+ "url": "https://500px.com/p/{}",
+ "urlMain": "https://500px.com/",
+ "urlProbe": "https://api.500px.com/graphql?operationName=ProfileRendererQuery&variables=%7B%22username%22%3A%22{}%22%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%224d02ff5c13927a3ac73b3eef306490508bc765956940c31051468cf30402a503%22%7D%7D",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Badoo
+As of 2021-01-13, Badoo returns false positives
+```json
+ "Badoo": {
+ "errorType": "status_code",
+ "url": "https://badoo.com/profile/{}",
+ "urlMain": "https://badoo.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Pling
+As of 2021-01-13, Pling returns false positives.
+```json
+ "Pling": {
+ "errorMsg": "Resource not found",
+ "errorType": "message",
+ "url": "https://www.pling.com/u/{}/",
+ "urlMain": "https://www.pling.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## Realmeye
+As of 2021-01-13, Realmeye returns false positives.
+```json
+ "Realmeye": {
+ "errorMsg": "Sorry, but we either:",
+ "errorType": "message",
+ "url": "https://www.realmeye.com/player/{}",
+ "urlMain": "https://www.realmeye.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Travellerspoint
+As of 2021-01-13, Travellerspoint returns false positives
+```json
+ "Travellerspoint": {
+ "errorMsg": "Wooops. Sorry!",
+ "errorType": "message",
+ "url": "https://www.travellerspoint.com/users/{}",
+ "urlMain": "https://www.travellerspoint.com",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## GDProfiles
+
+As of 2021-06-27, GDProfiles takes way too long to respond. Must be an issue on their side.
+```json
+ "GDProfiles": {
+ "errorType": "status_code",
+ "url": "https://gdprofiles.com/{}",
+ "urlMain": "https://gdprofiles.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## AllTrails
+
+As of 2021-06-27, AllTrails has a captcha which prevents us from checking for usernames on the site.
+```json
+ "AllTrails": {
+ "errorMsg": "class=\"home index\"",
+ "errorType": "message",
+ "url": "https://www.alltrails.com/members/{}",
+ "urlMain": "https://www.alltrails.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ }
+```
+
+## Cent
+
+As of 2021-06-27, there is not way of checking if a username exists on Cent
+
+```json
+ "Cent": {
+ "errorMsg": "Cent ",
+ "errorType": "message",
+ "url": "https://beta.cent.co/@{}",
+ "urlMain": "https://cent.co/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Anobii
+
+As of 2021-06-27, Anobii returns false positives and there is no stable way of checking usernames.
+```
+
+ "Anobii": {
+ "errorType": "response_url",
+ "url": "https://www.anobii.com/{}/profile",
+ "urlMain": "https://www.anobii.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Kali Community
+
+As of 2021-06-27, Kali Community requires us to be logged in order to check if a user exists on their forum.
+
+```json
+ "Kali community": {
+ "errorMsg": "This user has not registered and therefore does not have a profile to view.",
+ "errorType": "message",
+ "url": "https://forums.kali.org/member.php?username={}",
+ "urlMain": "https://forums.kali.org/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## NameMC
+
+As of 2021-06-27, NameMC uses captcha through CloudFlare which prevents us from checking if usernames exists on the site.
+
+```json
+ "NameMC (Minecraft.net skins)": {
+ "errorMsg": "Profiles: 0 results",
+ "errorType": "message",
+ "url": "https://namemc.com/profile/{}",
+ "urlMain": "https://namemc.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## SteamID
+
+As of 2021-06-27, Steam uses captcha through CloudFlare which prevents us from checking if usernames exists on the site.
+```json
+ "Steamid": {
+ "errorMsg": " ",
+ "errorType": "message",
+ "url": "https://steamid.uk/profile/{}",
+ "urlMain": "https://steamid.uk/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+
+## TripAdvisor
+
+As of 2021-06-27, Trip takes too long to return a response. As of now, the reason is not known.
+```json
+ "TripAdvisor": {
+ "errorMsg": "This page is on vacation\u2026",
+ "errorType": "message",
+ "url": "https://tripadvisor.com/members/{}",
+ "urlMain": "https://tripadvisor.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+
+```
+
+### House Mixes
+
+As of 2021-09-04, House Mixes has issues connecting causing Sherlock to freeze.
+```json
+ "House-Mixes.com": {
+ "errorMsg": "Profile Not Found",
+ "errorType": "message",
+ "regexCheck": "^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$",
+ "url": "https://www.house-mixes.com/profile/{}",
+ "urlMain": "https://www.house-mixes.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+### Quora
+As of 2021-09-04, Quora returns false positives.
+```json
+ "Quora": {
+ "errorMsg": "Page Not Found",
+ "errorType": "message",
+ "url": "https://www.quora.com/profile/{}",
+ "urlMain": "https://www.quora.com/",
+ "username_claimed": "Matt-Riggsby",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+### SparkPeople
+As of 2021-09-04, SparkPeople returns false positives.
+```json
+ "SparkPeople": {
+ "errorMsg": "We couldn't find that user",
+ "errorType": "message",
+ "url": "https://www.sparkpeople.com/mypage.asp?id={}",
+ "urlMain": "https://www.sparkpeople.com",
+ "username_claimed": "adam",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+### Cloob
+As of 2021-10-25, Cloob seems to be down and their site is not responding.
+```json
+ "Cloob": {
+ "errorType": "status_code",
+ "url": "https://www.cloob.com/name/{}",
+ "urlMain": "https://www.cloob.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+### TM-Ladder
+As of 2021-11-30, TM-Ladder is returning false positives due to rate limits.
+
+```json
+ "TM-Ladder": {
+ "errorMsg": "player unknown or invalid",
+ "errorType": "message",
+ "url": "http://en.tm-ladder.com/{}_rech.php",
+ "urlMain": "http://en.tm-ladder.com/index.php",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+```
+
+### plug.dj
+As of 2021-12-02, plug.dj is returning false positives because the service is down.
+
+```json
+ "plug.dj": {
+ "errorType": "status_code",
+ "url": "https://plug.dj/@/{}",
+ "urlMain": "https://plug.dj/",
+ "username_claimed": "plug-dj-rock",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Facenama
+
+As of 2022-02-6, Facenama seems to be down their rebuilding their site
+```json
+ "Facenama": {
+ "errorType": "response_url",
+ "errorUrl": "https://facenama.com/404.html",
+ "regexCheck": "^[-a-zA-Z0-9_]+$",
+ "url": "https://facenama.com/{}",
+ "urlMain": "https://facenama.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis77"
+ },
+```
+
+
+## Designspiration
+
+As of 2022-04-17, Designspiration seems to be down or very laggy. Therefore, we're removing the site for now.
+
+```json
+ "Designspiration": {
+ "errorType": "status_code",
+ "url": "https://www.designspiration.net/{}/",
+ "urlMain": "https://www.designspiration.net/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## CapFriendly
+
+As of 2022-05-01, CapFriendly always shows that a username exists even though it doesn't. This
+then of course causes false positives in Sherlock's results.
+
+```json
+ "CapFriendly": {
+ "errorMsg": "No results found
",
+ "errorType": "message",
+ "regexCheck": "^[a-zA-z][a-zA-Z0-9_]{2,79}$",
+ "url": "https://www.capfriendly.com/users/{}",
+ "urlMain": "https://www.capfriendly.com/",
+ "username_claimed": "thisactuallyexists",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Gab
+
+As of 2022-05-01, Gab returns false positives because they now use CloudFlare
+```json
+ "Gab": {
+ "errorMsg": "The page you are looking for isn't here.",
+ "errorType": "message",
+ "url": "https://gab.com/{}",
+ "urlMain": "https://gab.com",
+ "username_claimed": "a",
+ "username_unclaimed": "noonewouldeverusethis"
+ },
+```
+
+## FanCentro
+
+As of 2022-05-1, FanCentro returns false positives. Will later in new version of Sherlock.
+
+```json
+ "FanCentro": {
+ "errorMsg": "var environment",
+ "errorType": "message",
+ "url": "https://fancentro.com/{}",
+ "urlMain": "https://fancentro.com/",
+ "username_claimed": "nielsrosanna",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Smashcast
+As og 2022-05-01, Smashcast is down
+```json
+ "Smashcast": {
+ "errorType": "status_code",
+ "url": "https://www.smashcast.tv/api/media/live/{}",
+ "urlMain": "https://www.smashcast.tv/",
+ "username_claimed": "hello",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Countable
+
+As og 2022-05-01, Countable returns false positives
+```json
+ "Countable": {
+ "errorType": "status_code",
+ "url": "https://www.countable.us/{}",
+ "urlMain": "https://www.countable.us/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Raidforums
+
+Raidforums is [now run by the FBI](https://twitter.com/janomine/status/1499453777648234501?s=21)
+```json
+ "Raidforums": {
+ "errorType": "status_code",
+ "url": "https://raidforums.com/User-{}",
+ "urlMain": "https://raidforums.com/",
+ "username_claimed": "red",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Pinterest
+Removed due to false positive
+
+```json
+ "Pinterest": {
+ "errorType": "status_code",
+ "url": "https://www.pinterest.com/{}/",
+ "urlMain": "https://www.pinterest.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis76543"
+ }
+```
+
+## PCPartPicker
+As of 17-07-2022, PCPartPicker requires us to login in order to check if a user exits
+
+```json
+ "PCPartPicker": {
+ "errorType": "status_code",
+ "url": "https://pcpartpicker.com/user/{}",
+ "urlMain": "https://pcpartpicker.com",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Ebay
+As of 17-07-2022, Ebay is very slow to respond. It was also reported that it returned false positives. So this is something that has been investigated further later.
+
+```json
+ "eBay.com": {
+ "errorMsg": "The User ID you entered was not found. Please check the User ID and try again.",
+ "errorType": "message",
+ "url": "https://www.ebay.com/usr/{}",
+ "urlMain": "https://www.ebay.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+ "eBay.de": {
+ "errorMsg": "Der eingegebene Nutzername wurde nicht gefunden. Bitte pr\u00fcfen Sie den Nutzernamen und versuchen Sie es erneut.",
+ "errorType": "message",
+ "url": "https://www.ebay.de/usr/{}",
+ "urlMain": "https://www.ebay.de/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Ghost
+As of 17-07-2022, Ghost returns false positives
+
+```json
+ "Ghost": {
+ "errorMsg": "Domain Error",
+ "errorType": "message",
+ "url": "https://{}.ghost.io/",
+ "urlMain": "https://ghost.org/",
+ "username_claimed": "troyhunt",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Atom Discussions
+As of 25-07-2022, Atom Discussions seems to not work beceause it keeps on
+redirecting to github discussion tab which does not exist and is not specific to a username
+
+```json
+ "Atom Discussions": {
+ "errorMsg": "Oops! That page doesn\u2019t exist or is private.",
+ "errorType": "message",
+ "url": "https://discuss.atom.io/u/{}/summary",
+ "urlMain": "https://discuss.atom.io",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis"
+ }
+```
+
+## Gam1ng
+As of 25-07-2022, Gam1ng has been permanently moved and is no longer functional
+
+```json
+ "Gam1ng": {
+ "errorType": "status_code",
+ "url": "https://gam1ng.com.br/user/{}",
+ "urlMain": "https://gam1ng.com.br",
+ "username_claimed": "PinKgirl",
+ "username_unclaimed": "noonewouldeverusethis77777"
+ }
+```
+
+## OGUsers
+As of 25-07-2022, OGUsers is now no longer functional
+
+```json
+ "OGUsers": {
+ "errorType": "status_code",
+ "url": "https://ogusers.com/{}",
+ "urlMain": "https://ogusers.com/",
+ "username_claimed": "ogusers",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## Otzovik
+As of 25-07-2022, Otzovik is now no longer functional
+
+```json
+ "Otzovik": {
+ "errorType": "status_code",
+ "url": "https://otzovik.com/profile/{}",
+ "urlMain": "https://otzovik.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## radio_echo_msk
+As of 25-07-2022, radio_echo_msk is now no longer functional
+
+```json
+ "radio_echo_msk": {
+ "errorType": "status_code",
+ "url": "https://echo.msk.ru/users/{}",
+ "urlMain": "https://echo.msk.ru/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+## Ello
+As of 06.09.2022, Ello is now behind CloudFlare
+```json
+ "Ello": {
+ "errorMsg": "We couldn't find the page you're looking for",
+ "errorType": "message",
+ "url": "https://ello.co/{}",
+ "urlMain": "https://ello.co/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ }
+```
+
+## GitHub Support Community
+As of 06.09.2022, GitHub Support Community's endpoint just redirects to the main community page
+```json
+ "GitHub Support Community": {
+ "errorMsg": "Oops! That page doesn\u2019t exist or is private.",
+ "errorType": "message",
+ "url": "https://github.community/u/{}/summary",
+ "urlMain": "https://github.community",
+ "username_claimed": "jperl",
+ "username_unclaimed": "noonewouldusethis298"
+ }
+```
+
+## GuruShots
+As of 08.09.2022, GuruShots returns false positives because it just returns a blank page. Need to look further into it so that it can be added back.
+
+```json
+ "GuruShots": {
+ "errorType": "status_code",
+ "url": "https://gurushots.com/{}/photos",
+ "urlMain": "https://gurushots.com/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Google Developer
+As of 09.10.2022, Google Developer returns false positives. The site is dynamic so we're not abl to get any proper results
+
+```json
+ "Google Developer": {
+ "errorMsg": "Sorry, the profile was not found.",
+ "errorType": "message",
+ "url": "https://g.dev/{}",
+ "urlMain": "https://g.dev/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## mastodon.technology
+As of 18.12.2022, mastodon.technology has no A/AAAA records and the [website was shut down by the owner](https://ashfurrow.com/blog/mastodon-technology-shutdown/).
+
+```json
+ "mastodon.technology": {
+ "errorType": "status_code",
+ "url": "https://mastodon.technology/@{}",
+ "urlMain": "https://mastodon.xyz/",
+ "username_claimed": "ashfurrow",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+
+## Aruino
+As of 04.02.2023, Arduino returns false positives. Finding a fix is doable but takes some time. Will be fixed later
+
+```json
+"Arduino": {
+ "errorMsg":"Arduino Cloud ",
+ "errorType": "message",
+ "regexCheck": "^(?![_-])[A-Za-z0-9_-]{3,}$",
+ "url": "https://projecthub.arduino.cc/{}",
+ "urlMain": "https://www.arduino.cc/",
+ "username_claimed": "blue",
+ "username_unclaimed": "noonewould"
+ },
+
+```
+
+## Zoomit
+As of 04.02.2023, Zoomit return false positves. An attempt at finding a fix was made but a lot of time was used without luck. Therefore, it wont be prioritized at the moment.
+```json
+ "zoomit": {
+ "errorMsg": "\u0645\u062a\u0627\u0633\u0641\u0627\u0646\u0647 \u0635\u0641\u062d\u0647 \u06cc\u0627\u0641\u062a \u0646\u0634\u062f",
+ "errorType": "message",
+ "url": "https://www.zoomit.ir/user/{}",
+ "urlMain": "https://www.zoomit.ir",
+ "username_claimed": "kossher",
+ "username_unclaimed": "noonewouldeverusethis7"
+ },
+```
+
+## Facebook
+As of 04.02.2023, Facebook returns false positives because we get prompted with the login screen to view the data
+```json
+"Facebook": {
+ "errorType": "status_code",
+ "regexCheck": "^[a-zA-Z0-9\\.]{3,49}(?Tinder | Dating, Make Friends & Meet New People",
+ "Tinder | Match. Chat. Date. "
+ ],
+ "errorType": "message",
+ "url": "https://www.tinder.com/@{}",
+ "urlMain": "https://tinder.com/",
+ "username_claimed": "blue"
+ },
+```
+
+
+## Coil
+As of 2023.03.15, Coil has been discontinued. All accounts were deleted and any requests return a 404.
+
+```json
+"Coil": {
+ "errorMsg": "User not found",
+ "errorType": "message",
+ "request_method": "POST",
+ "request_payload": {
+ "operationName": "getCreator",
+ "query": "query getCreator($userShortName:String!){getCreator(userShortName:$userShortName){id}}",
+ "variables": {
+ "userShortName": "{}"
+ }
+ },
+ "url": "https://coil.com/u/{}",
+ "urlMain": "https://coil.com/",
+ "urlProbe": "https://coil.com/gateway",
+ "username_claimed": "adam"
+ }
+```
+
+## OnlyFans
+As of 2023.04.20, OnlyFans returns false negatives on checking usernames with the API endpoint and directly through their website.
+
+```json
+"OnlyFans": {
+ "errorType": "status_code",
+ "isNSFW": true,
+ "url": "https://onlyfans.com/{}",
+ "urlMain": "https://onlyfans.com/",
+ "urlProbe": "https://onlyfans.com/api2/v2/users/{}",
+ "username_claimed": "theemilylynne"
+ }
+```
+
+## OK
+As of 2023.04.21, Ok.ru returns false positives
+```json
+ "OK": {
+ "errorType": "status_code",
+ "regexCheck": "^[a-zA-Z][a-zA-Z0-9_.-]*$",
+ "url": "https://ok.ru/{}",
+ "urlMain": "https://ok.ru/",
+ "username_claimed": "ok"
+ }
+```
+
+## ForumhouseRU
+As of 2023.04.21, ForumhouseRU returns false positives
+```json
+ "forumhouseRU": {
+ "errorMsg": "\u0423\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0434\u0440\u0443\u0433\u043e\u0435 \u0438\u043c\u044f.",
+ "errorType": "message",
+ "url": "https://www.forumhouse.ru/members/?username={}",
+ "urlMain": "https://www.forumhouse.ru/",
+ "username_claimed": "red"
+ }
+```
+
+## Enjin
+As of 2023.08.29, Enjin has closed down.
+
+```json
+"Enjin": {
+ "errorMsg": "Yikes, there seems to have been an error. We've taken note and will check out the problem right away!",
+ "errorType": "message",
+ "url": "https://www.enjin.com/profile/{}",
+ "urlMain": "https://www.enjin.com/",
+ "username_claimed": "blue"
+ },
+```
+
+## IRL
+As of 2023.08.29, IRL has shut down
+```json
+ "IRL": {
+ "errorType": "status_code",
+ "url": "https://www.irl.com/{}",
+ "urlMain": "https://www.irl.com/",
+ "username_claimed": "hacker"
+ }
+```
+
+## Munzee
+As of 2023.08.29, Munzee requires us to be logged into the site in order to check if a user exists or not
+```json
+ "Munzee": {
+ "errorType": "status_code",
+ "url": "https://www.munzee.com/m/{}",
+ "urlMain": "https://www.munzee.com/",
+ "username_claimed": "blue"
+ }
+```
+
+## Quizlet
+As of 2023.08.29 Quizlet requires us to enable JavaScript to check if a user exsits on the website
+
+```json
+"Quizlet": {
+ "errorMsg": "Page Unavailable",
+ "errorType": "message",
+ "url": "https://quizlet.com/{}",
+ "urlMain": "https://quizlet.com",
+ "username_claimed": "blue"
+ }
+```
+
+## GunsAndAmmo
+As of 2023.08.29, GunsAndAmmo responds with 404 from time to time
+```json
+ "GunsAndAmmo": {
+ "errorType": "status_code",
+ "url": "https://forums.gunsandammo.com/profile/{}",
+ "urlMain": "https://gunsandammo.com/",
+ "username_claimed": "adam"
+ }
+```
+
+## TikTok
+As of 2023.12.21, TikTok returns false positives. This is because the webpage returns a somewhat blank page. This prevents us from being able to check for the existence of usernames. Proxitok does not work either.
+
+```json
+ "TikTok": {
+ "errorType": "status_code",
+ "url": "https://tiktok.com/@{}",
+ "urlMain": "https://tiktok.com/",
+ "username_claimed": "red"
+ },
+```
+
+## Lolchess
+As of 2023.12.21, Lolchess returns false positives.
+```json
+ "Lolchess": {
+ "errorMsg": "No search results",
+ "errorType": "message",
+ "url": "https://lolchess.gg/profile/na/{}",
+ "urlMain": "https://lolchess.gg/",
+ "username_claimed": "blue"
+ },
+```
+
+## Virgool
+As of 2023.12.21, Virgool returns false positives.
+```json
+ "Virgool": {
+ "errorMsg": "\u06f4\u06f0\u06f4",
+ "errorType": "message",
+ "url": "https://virgool.io/@{}",
+ "urlMain": "https://virgool.io/",
+ "username_claimed": "blue"
+ },
+```
+
+## Whonix Forum
+As of 2023.12.21, Whonix Forum returns false positives.
+```json
+ "Whonix Forum": {
+ "errorType": "status_code",
+ "url": "https://forums.whonix.org/u/{}/summary",
+ "urlMain": "https://forums.whonix.org/",
+ "username_claimed": "red"
+ },
+```
+
+## Ebio
+As of 2023.12.21, Ebio returns false positives.
+```json
+ "ebio.gg": {
+ "errorType": "status_code",
+ "url": "https://ebio.gg/{}",
+ "urlMain": "https:/ebio.gg",
+ "username_claimed": "dev"
+ },
+```
+
+## HexRPG
+__2024-04-07 :__ HexRPG behind authentication wall. Unable to check usernames without logging in.
+```json
+ "HexRPG": {
+ "errorMsg": "Error : User ",
+ "errorType": "message",
+ "regexCheck": "^[a-zA-Z0-9_ ]{3,20}$",
+ "url": "https://www.hexrpg.com/userinfo/{}",
+ "urlMain": "https://www.hexrpg.com/",
+ "username_claimed": "blue"
+ }
+```
+
+## Oracle Communities
+__2024-04-07 :__ Oracle Communities behind authentication wall. Unable to check usernames without logging in.
+```json
+ "Oracle Communities": {
+ "errorType": "status_code",
+ "url": "https://community.oracle.com/people/{}",
+ "urlMain": "https://community.oracle.com",
+ "username_claimed": "dev"
+ }
+```
+
+## Metacritic
+__2024-04-07 :__ Non-existent users seemingly displayed as real users with no activity. Needs adjustment.
+```json
+ "metacritic": {
+ "errorMsg": "User not found",
+ "errorType": "message",
+ "regexCheck": "^(?![-_].)[A-Za-z0-9-_]{3,15}$",
+ "url": "https://www.metacritic.com/user/{}",
+ "urlMain": "https://www.metacritic.com/",
+ "username_claimed": "blue"
+ }
+```
+
+## G2G
+__2024-04-10 :__ Seems to be loading profiles with some wierd javascript setup that sherlock doesn't like, leading to difficult to control false positives
+```json
+ "G2G": {
+ "errorType": "response_url",
+ "errorUrl": "https://www.g2g.com/{}",
+ "regexCheck": "^[A-Za-z][A-Za-z0-9_]{2,11}$",
+ "url": "https://www.g2g.com/{}",
+ "urlMain": "https://www.g2g.com/",
+ "username_claimed": "user"
+ }
+```
+
+## Bitcoin Forum
+__2024-04-24 :__ BCF seems to have gone defunct. Uncertain.
+```json
+"BitCoinForum": {
+ "errorMsg": "The user whose profile you are trying to view does not exist.",
+ "errorType": "message",
+ "url": "https://bitcoinforum.com/profile/{}",
+ "urlMain": "https://bitcoinforum.com",
+ "username_claimed": "bitcoinforum.com"
+ }
+```
+
+## Zhihu
+As of 24.06.2024, Zhihu returns false positives as they obfuscate the code thats returned. Checking for patterns may allow us to find a way to detect the existans of a user, this will be need to be worked on later
+```json
+
+ "Zhihu": {
+ "errorMsg": "用户不存在",
+ "errorType": "message",
+ "url": "https://www.zhihu.com/people/{}",
+ "urlMain": "https://www.zhihu.com/",
+ "username_claimed": "blue"
+ }
+```
+
+## Penetestit
+
+As of 24.06.2024, Pentestit returns a 403. This is most likely due to a new site structures
+
+```json
+ "labpentestit": {
+ "errorType": "response_url",
+ "errorUrl": "https://lab.pentestit.ru/{}",
+ "url": "https://lab.pentestit.ru/profile/{}",
+ "urlMain": "https://lab.pentestit.ru/",
+ "username_claimed": "CSV"
+ }
+```
+
+
+## Euw
+__2024-06-09 :__ errorMsg detection doesn't work anymore, because the error message is included in HTTP request body, even in successful search
+```json
+"Euw": {
+ "errorMsg": "This summoner is not registered at OP.GG. Please check spelling.",
+ "errorType": "message",
+ "url": "https://euw.op.gg/summoner/userName={}",
+ "urlMain": "https://euw.op.gg/",
+ "username_claimed": "blue"
+ }
+```
+
+## Etsy
+__2024-06-10 :__ Http request returns 403 forbidden, and tries to verify the connection, so it doesn't work anymore
+```json
+"Etsy": {
+ "errorType": "status_code",
+ "url": "https://www.etsy.com/shop/{}",
+ "urlMain": "https://www.etsy.com/",
+ "username_claimed": "JennyKrafts"
+ }
+```
+
+## Alik.cz
+__2024-07-21 :__ Target is now BLACKLISTED from the default manifest due to the site recieving unnecessarily high traffic from Sherlock (by request of the site owners). This target is not permitted to be reactivited. Inclusion in unrelated manifests is not impacted, but it is discouraged.
+
+## 8tracks
+__2025-02-02 :__ Might be dead again. Nobody knows for sure.
+```json
+"8tracks": {
+ "errorType": "message",
+ "errorMsg": "\"available\":true",
+ "headers": {
+ "Accept-Language": "en-US,en;q=0.5"
+ },
+ "url": "https://8tracks.com/{}",
+ "urlProbe": "https://8tracks.com/users/check_username?login={}&format=jsonh",
+ "urlMain": "https://8tracks.com/",
+ "username_claimed": "blue"
+ }
+```
+
+## Shpock
+__2025-02-02 :__ Can likely be added back with a new endpoint (source username availability endpoint from mobile app reg flow?)
+```json
+"Shpock": {
+ "errorType": "status_code",
+ "url": "https://www.shpock.com/shop/{}/items",
+ "urlMain": "https://www.shpock.com/",
+ "username_claimed": "user"
+ }
+```
+
+## Twitch
+__2025-02-02 :__
+```json
+"Twitch": {
+ "errorType": "message",
+ "errorMsg": "components.availability-tracking.warn-unavailable.component",
+ "url": "https://www.twitch.tv/{}",
+ "urlMain": "https://www.twitch.tv/",
+ "urlProbe": "https://m.twitch.tv/{}",
+ "username_claimed": "jenny"
+ }
+```
+
+## Fiverr
+__2025-02-02 :__ Fiverr added CSRF protections that messed with this test
+```json
+"Fiverr": {
+ "errorMsg": "\"status\":\"success\"",
+ "errorType": "message",
+ "headers": {
+ "Content-Type": "application/json",
+ "Accept-Language": "en-US,en;q=0.9"
+ },
+ "regexCheck": "^[A-Za-z][A-Za-z\\d_]{5,14}$",
+ "request_method": "POST",
+ "request_payload": {
+ "username": "{}"
+ },
+ "url": "https://www.fiverr.com/{}",
+ "urlMain": "https://www.fiverr.com/",
+ "urlProbe": "https://www.fiverr.com/validate_username",
+ "username_claimed": "blueman"
+ }
+```
+
+## BabyRU
+__2025-02-02 :__ Just being problematic (possibly related to errorMsg encoding?)
+```json
+"babyRU": {
+ "errorMsg": [
+ "\u0421\u0442\u0440\u0430\u043d\u0438\u0446\u0430, \u043a\u043e\u0442\u043e\u0440\u0443\u044e \u0432\u044b \u0438\u0441\u043a\u0430\u043b\u0438, \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u0430",
+ "Доступ с вашего IP-адреса временно ограничен"
+ ],
+ "errorType": "message",
+ "url": "https://www.baby.ru/u/{}/",
+ "urlMain": "https://www.baby.ru/",
+ "username_claimed": "blue"
+ }
+```
+
+## v0.dev
+__2025-02-16 :__ Unsure if any way to view profiles exists now
+```json
+"v0.dev": {
+ "errorType": "message",
+ "errorMsg": "v0 by Vercel ",
+ "url": "https://v0.dev/{}",
+ "urlMain": "https://v0.dev",
+ "username_claimed": "t3dotgg"
+ }
+```
+
+## TorrentGalaxy
+__2025-07-06 :__ Site appears to have gone offline in March and hasn't come back
+```json
+ "TorrentGalaxy": {
+ "errorMsg": "TGx:Can't show details ",
+ "errorType": "message",
+ "regexCheck": "^[A-Za-z0-9]{3,15}$",
+ "url": "https://torrentgalaxy.to/profile/{}",
+ "urlMain": "https://torrentgalaxy.to/",
+ "username_claimed": "GalaxyRG"
+ },
+```
diff --git a/sherlock/pyproject.toml b/sherlock/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..e6b059355091588fa686de51a29b341a07247765
--- /dev/null
+++ b/sherlock/pyproject.toml
@@ -0,0 +1,68 @@
+[build-system]
+requires = [ "poetry-core>=1.2.0" ]
+build-backend = "poetry.core.masonry.api"
+# poetry-core 1.8 not available in .fc39. Can upgrade to 1.8.0 at .fc39 EOL
+
+[tool.poetry-version-plugin]
+source = "init"
+
+[tool.poetry]
+name = "sherlock-project"
+version = "0.16.0"
+description = "Hunt down social media accounts by username across social networks"
+license = "MIT"
+authors = [
+ "Siddharth Dushantha "
+]
+maintainers = [
+ "Paul Pfeister ",
+ "Matheus Felipe ",
+ "Sondre Karlsen Dyrnes "
+]
+readme = "docs/pyproject/README.md"
+packages = [ { include = "sherlock_project"} ]
+keywords = [ "osint", "reconnaissance", "information gathering" ]
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Information Technology",
+ "Natural Language :: English",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Topic :: Security"
+]
+homepage = "https://sherlockproject.xyz/"
+repository = "https://github.com/sherlock-project/sherlock"
+
+
+[tool.poetry.urls]
+"Bug Tracker" = "https://github.com/sherlock-project/sherlock/issues"
+
+[tool.poetry.dependencies]
+python = "^3.9"
+certifi = ">=2019.6.16"
+colorama = "^0.4.1"
+PySocks = "^1.7.0"
+requests = "^2.22.0"
+requests-futures = "^1.0.0"
+stem = "^1.8.0"
+pandas = "^2.2.1"
+openpyxl = "^3.0.10"
+tomli = "^2.2.1"
+
+[tool.poetry.group.dev.dependencies]
+jsonschema = "^4.0.0"
+rstr = "^3.2.2"
+pytest = "^8.4.2"
+pytest-xdist = "^3.8.0"
+
+
+[tool.poetry.group.ci.dependencies]
+defusedxml = "^0.7.1"
+
+[tool.poetry.scripts]
+sherlock = 'sherlock_project.sherlock:main'
diff --git a/sherlock/pytest.ini b/sherlock/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..1f521b8290c39bfe850c29dfc3b3a12db2f788a0
--- /dev/null
+++ b/sherlock/pytest.ini
@@ -0,0 +1,7 @@
+[pytest]
+addopts = --strict-markers -m "not validate_targets"
+markers =
+ online: mark tests are requiring internet access.
+ validate_targets: mark tests for sweeping manifest validation (sends many requests).
+ validate_targets_fp: validate_targets, false positive tests only.
+ validate_targets_fn: validate_targets, false negative tests only.
diff --git a/sherlock/sherlock_project/__init__.py b/sherlock/sherlock_project/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd992a4247818d0a8d140e30d20daa214a169775
--- /dev/null
+++ b/sherlock/sherlock_project/__init__.py
@@ -0,0 +1,30 @@
+""" Sherlock Module
+
+This module contains the main logic to search for usernames at social
+networks.
+
+"""
+
+from importlib.metadata import version as pkg_version, PackageNotFoundError
+import pathlib
+import tomli
+
+
+def get_version() -> str:
+ """Fetch the version number of the installed package."""
+ try:
+ return pkg_version("sherlock_project")
+ except PackageNotFoundError:
+ pyproject_path: pathlib.Path = pathlib.Path(__file__).resolve().parent.parent / "pyproject.toml"
+ with pyproject_path.open("rb") as f:
+ pyproject_data = tomli.load(f)
+ return pyproject_data["tool"]["poetry"]["version"]
+
+# This variable is only used to check for ImportErrors induced by users running as script rather than as module or package
+import_error_test_var = None
+
+__shortname__ = "Sherlock"
+__longname__ = "Sherlock: Find Usernames Across Social Networks"
+__version__ = get_version()
+
+forge_api_latest_release = "https://api.github.com/repos/sherlock-project/sherlock/releases/latest"
diff --git a/sherlock/sherlock_project/__main__.py b/sherlock/sherlock_project/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d62f1ad0bd53f32d83c672067d6e273b43a4409c
--- /dev/null
+++ b/sherlock/sherlock_project/__main__.py
@@ -0,0 +1,22 @@
+#! /usr/bin/env python3
+
+"""
+Sherlock: Find Usernames Across Social Networks Module
+
+This module contains the main logic to search for usernames at social
+networks.
+"""
+
+import sys
+
+
+if __name__ == "__main__":
+ # Check if the user is using the correct version of Python
+ python_version = sys.version.split()[0]
+
+ if sys.version_info < (3, 9):
+ print(f"Sherlock requires Python 3.9+\nYou are using Python {python_version}, which is not supported by Sherlock.")
+ sys.exit(1)
+
+ from sherlock_project import sherlock
+ sherlock.main()
diff --git a/sherlock/sherlock_project/notify.py b/sherlock/sherlock_project/notify.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1fc00ab71f527b2b725c501a31882f87693535e
--- /dev/null
+++ b/sherlock/sherlock_project/notify.py
@@ -0,0 +1,286 @@
+"""Sherlock Notify Module
+
+This module defines the objects for notifying the caller about the
+results of queries.
+"""
+from sherlock_project.result import QueryStatus
+from colorama import Fore, Style
+import webbrowser
+
+# Global variable to count the number of results.
+globvar = 0
+
+
+class QueryNotify:
+ """Query Notify Object.
+
+ Base class that describes methods available to notify the results of
+ a query.
+ It is intended that other classes inherit from this base class and
+ override the methods to implement specific functionality.
+ """
+
+ def __init__(self, result=None):
+ """Create Query Notify Object.
+
+ Contains information about a specific method of notifying the results
+ of a query.
+
+ Keyword Arguments:
+ self -- This object.
+ result -- Object of type QueryResult() containing
+ results for this query.
+
+ Return Value:
+ Nothing.
+ """
+
+ self.result = result
+
+ # return
+
+ def start(self, message=None):
+ """Notify Start.
+
+ Notify method for start of query. This method will be called before
+ any queries are performed. This method will typically be
+ overridden by higher level classes that will inherit from it.
+
+ Keyword Arguments:
+ self -- This object.
+ message -- Object that is used to give context to start
+ of query.
+ Default is None.
+
+ Return Value:
+ Nothing.
+ """
+
+ # return
+
+ def update(self, result):
+ """Notify Update.
+
+ Notify method for query result. This method will typically be
+ overridden by higher level classes that will inherit from it.
+
+ Keyword Arguments:
+ self -- This object.
+ result -- Object of type QueryResult() containing
+ results for this query.
+
+ Return Value:
+ Nothing.
+ """
+
+ self.result = result
+
+ # return
+
+ def finish(self, message=None):
+ """Notify Finish.
+
+ Notify method for finish of query. This method will be called after
+ all queries have been performed. This method will typically be
+ overridden by higher level classes that will inherit from it.
+
+ Keyword Arguments:
+ self -- This object.
+ message -- Object that is used to give context to start
+ of query.
+ Default is None.
+
+ Return Value:
+ Nothing.
+ """
+
+ # return
+
+ def __str__(self):
+ """Convert Object To String.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Nicely formatted string to get information about this object.
+ """
+ return str(self.result)
+
+
+class QueryNotifyPrint(QueryNotify):
+ """Query Notify Print Object.
+
+ Query notify class that prints results.
+ """
+
+ def __init__(self, result=None, verbose=False, print_all=False, browse=False):
+ """Create Query Notify Print Object.
+
+ Contains information about a specific method of notifying the results
+ of a query.
+
+ Keyword Arguments:
+ self -- This object.
+ result -- Object of type QueryResult() containing
+ results for this query.
+ verbose -- Boolean indicating whether to give verbose output.
+ print_all -- Boolean indicating whether to only print all sites, including not found.
+ browse -- Boolean indicating whether to open found sites in a web browser.
+
+ Return Value:
+ Nothing.
+ """
+
+ super().__init__(result)
+ self.verbose = verbose
+ self.print_all = print_all
+ self.browse = browse
+
+ return
+
+ def start(self, message):
+ """Notify Start.
+
+ Will print the title to the standard output.
+
+ Keyword Arguments:
+ self -- This object.
+ message -- String containing username that the series
+ of queries are about.
+
+ Return Value:
+ Nothing.
+ """
+
+ title = "Checking username"
+
+ print(Style.BRIGHT + Fore.GREEN + "[" +
+ Fore.YELLOW + "*" +
+ Fore.GREEN + f"] {title}" +
+ Fore.WHITE + f" {message}" +
+ Fore.GREEN + " on:")
+ # An empty line between first line and the result(more clear output)
+ print('\r')
+
+ return
+
+ def countResults(self):
+ """This function counts the number of results. Every time the function is called,
+ the number of results is increasing.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ The number of results by the time we call the function.
+ """
+ global globvar
+ globvar += 1
+ return globvar
+
+ def update(self, result):
+ """Notify Update.
+
+ Will print the query result to the standard output.
+
+ Keyword Arguments:
+ self -- This object.
+ result -- Object of type QueryResult() containing
+ results for this query.
+
+ Return Value:
+ Nothing.
+ """
+ self.result = result
+
+ response_time_text = ""
+ if self.result.query_time is not None and self.verbose is True:
+ response_time_text = f" [{round(self.result.query_time * 1000)}ms]"
+
+ # Output to the terminal is desired.
+ if result.status == QueryStatus.CLAIMED:
+ self.countResults()
+ print(Style.BRIGHT + Fore.WHITE + "[" +
+ Fore.GREEN + "+" +
+ Fore.WHITE + "]" +
+ response_time_text +
+ Fore.GREEN +
+ f" {self.result.site_name}: " +
+ Style.RESET_ALL +
+ f"{self.result.site_url_user}")
+ if self.browse:
+ webbrowser.open(self.result.site_url_user, 2)
+
+ elif result.status == QueryStatus.AVAILABLE:
+ if self.print_all:
+ print(Style.BRIGHT + Fore.WHITE + "[" +
+ Fore.RED + "-" +
+ Fore.WHITE + "]" +
+ response_time_text +
+ Fore.GREEN + f" {self.result.site_name}:" +
+ Fore.YELLOW + " Not Found!")
+
+ elif result.status == QueryStatus.UNKNOWN:
+ if self.print_all:
+ print(Style.BRIGHT + Fore.WHITE + "[" +
+ Fore.RED + "-" +
+ Fore.WHITE + "]" +
+ Fore.GREEN + f" {self.result.site_name}:" +
+ Fore.RED + f" {self.result.context}" +
+ Fore.YELLOW + " ")
+
+ elif result.status == QueryStatus.ILLEGAL:
+ if self.print_all:
+ msg = "Illegal Username Format For This Site!"
+ print(Style.BRIGHT + Fore.WHITE + "[" +
+ Fore.RED + "-" +
+ Fore.WHITE + "]" +
+ Fore.GREEN + f" {self.result.site_name}:" +
+ Fore.YELLOW + f" {msg}")
+
+ elif result.status == QueryStatus.WAF:
+ if self.print_all:
+ print(Style.BRIGHT + Fore.WHITE + "[" +
+ Fore.RED + "-" +
+ Fore.WHITE + "]" +
+ Fore.GREEN + f" {self.result.site_name}:" +
+ Fore.RED + " Blocked by bot detection" +
+ Fore.YELLOW + " (proxy may help)")
+
+ else:
+ # It should be impossible to ever get here...
+ raise ValueError(
+ f"Unknown Query Status '{result.status}' for site '{self.result.site_name}'"
+ )
+
+ return
+
+ def finish(self, message="The processing has been finished."):
+ """Notify Start.
+ Will print the last line to the standard output.
+ Keyword Arguments:
+ self -- This object.
+ message -- The 2 last phrases.
+ Return Value:
+ Nothing.
+ """
+ NumberOfResults = self.countResults() - 1
+
+ print(Style.BRIGHT + Fore.GREEN + "[" +
+ Fore.YELLOW + "*" +
+ Fore.GREEN + "] Search completed with" +
+ Fore.WHITE + f" {NumberOfResults} " +
+ Fore.GREEN + "results" + Style.RESET_ALL
+ )
+
+ def __str__(self):
+ """Convert Object To String.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Nicely formatted string to get information about this object.
+ """
+ return str(self.result)
diff --git a/sherlock/sherlock_project/py.typed b/sherlock/sherlock_project/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/sherlock/sherlock_project/result.py b/sherlock/sherlock_project/result.py
new file mode 100644
index 0000000000000000000000000000000000000000..e53dc0a0659160afee9efa7a225b94514247d71a
--- /dev/null
+++ b/sherlock/sherlock_project/result.py
@@ -0,0 +1,89 @@
+"""Sherlock Result Module
+
+This module defines various objects for recording the results of queries.
+"""
+from enum import Enum
+
+
+class QueryStatus(Enum):
+ """Query Status Enumeration.
+
+ Describes status of query about a given username.
+ """
+ CLAIMED = "Claimed" # Username Detected
+ AVAILABLE = "Available" # Username Not Detected
+ UNKNOWN = "Unknown" # Error Occurred While Trying To Detect Username
+ ILLEGAL = "Illegal" # Username Not Allowable For This Site
+ WAF = "WAF" # Request blocked by WAF (i.e. Cloudflare)
+
+ def __str__(self):
+ """Convert Object To String.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Nicely formatted string to get information about this object.
+ """
+ return self.value
+
+class QueryResult():
+ """Query Result Object.
+
+ Describes result of query about a given username.
+ """
+ def __init__(self, username, site_name, site_url_user, status,
+ query_time=None, context=None):
+ """Create Query Result Object.
+
+ Contains information about a specific method of detecting usernames on
+ a given type of web sites.
+
+ Keyword Arguments:
+ self -- This object.
+ username -- String indicating username that query result
+ was about.
+ site_name -- String which identifies site.
+ site_url_user -- String containing URL for username on site.
+ NOTE: The site may or may not exist: this
+ just indicates what the name would
+ be, if it existed.
+ status -- Enumeration of type QueryStatus() indicating
+ the status of the query.
+ query_time -- Time (in seconds) required to perform query.
+ Default of None.
+ context -- String indicating any additional context
+ about the query. For example, if there was
+ an error, this might indicate the type of
+ error that occurred.
+ Default of None.
+
+ Return Value:
+ Nothing.
+ """
+
+ self.username = username
+ self.site_name = site_name
+ self.site_url_user = site_url_user
+ self.status = status
+ self.query_time = query_time
+ self.context = context
+
+ return
+
+ def __str__(self):
+ """Convert Object To String.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Nicely formatted string to get information about this object.
+ """
+ status = str(self.status)
+ if self.context is not None:
+ # There is extra context information available about the results.
+ # Append it to the normal response text.
+ status += f" ({self.context})"
+
+ return status
diff --git a/sherlock/sherlock_project/sherlock.py b/sherlock/sherlock_project/sherlock.py
new file mode 100644
index 0000000000000000000000000000000000000000..898ff92d38fed3a7d74c9cb01910f7361d3cc54e
--- /dev/null
+++ b/sherlock/sherlock_project/sherlock.py
@@ -0,0 +1,942 @@
+#! /usr/bin/env python3
+
+"""
+Sherlock: Find Usernames Across Social Networks Module
+
+This module contains the main logic to search for usernames at social
+networks.
+"""
+
+import sys
+
+try:
+ from sherlock_project.__init__ import import_error_test_var # noqa: F401
+except ImportError:
+ print("Did you run Sherlock with `python3 sherlock/sherlock.py ...`?")
+ print("This is an outdated method. Please see https://sherlockproject.xyz/installation for up to date instructions.")
+ sys.exit(1)
+
+import csv
+import signal
+import pandas as pd
+import os
+import re
+from argparse import ArgumentParser, RawDescriptionHelpFormatter
+from json import loads as json_loads
+from time import monotonic
+from typing import Optional
+
+import requests
+from requests_futures.sessions import FuturesSession
+
+from sherlock_project.__init__ import (
+ __longname__,
+ __shortname__,
+ __version__,
+ forge_api_latest_release,
+)
+
+from sherlock_project.result import QueryStatus
+from sherlock_project.result import QueryResult
+from sherlock_project.notify import QueryNotify
+from sherlock_project.notify import QueryNotifyPrint
+from sherlock_project.sites import SitesInformation
+from colorama import init
+from argparse import ArgumentTypeError
+
+
+class SherlockFuturesSession(FuturesSession):
+ def request(self, method, url, hooks=None, *args, **kwargs):
+ """Request URL.
+
+ This extends the FuturesSession request method to calculate a response
+ time metric to each request.
+
+ It is taken (almost) directly from the following Stack Overflow answer:
+ https://github.com/ross/requests-futures#working-in-the-background
+
+ Keyword Arguments:
+ self -- This object.
+ method -- String containing method desired for request.
+ url -- String containing URL for request.
+ hooks -- Dictionary containing hooks to execute after
+ request finishes.
+ args -- Arguments.
+ kwargs -- Keyword arguments.
+
+ Return Value:
+ Request object.
+ """
+ # Record the start time for the request.
+ if hooks is None:
+ hooks = {}
+ start = monotonic()
+
+ def response_time(resp, *args, **kwargs):
+ """Response Time Hook.
+
+ Keyword Arguments:
+ resp -- Response object.
+ args -- Arguments.
+ kwargs -- Keyword arguments.
+
+ Return Value:
+ Nothing.
+ """
+ resp.elapsed = monotonic() - start
+
+ return
+
+ # Install hook to execute when response completes.
+ # Make sure that the time measurement hook is first, so we will not
+ # track any later hook's execution time.
+ try:
+ if isinstance(hooks["response"], list):
+ hooks["response"].insert(0, response_time)
+ elif isinstance(hooks["response"], tuple):
+ # Convert tuple to list and insert time measurement hook first.
+ hooks["response"] = list(hooks["response"])
+ hooks["response"].insert(0, response_time)
+ else:
+ # Must have previously contained a single hook function,
+ # so convert to list.
+ hooks["response"] = [response_time, hooks["response"]]
+ except KeyError:
+ # No response hook was already defined, so install it ourselves.
+ hooks["response"] = [response_time]
+
+ return super(SherlockFuturesSession, self).request(
+ method, url, hooks=hooks, *args, **kwargs
+ )
+
+
+def get_response(request_future, error_type, social_network):
+ # Default for Response object if some failure occurs.
+ response = None
+
+ error_context = "General Unknown Error"
+ exception_text = None
+ try:
+ response = request_future.result()
+ if response.status_code:
+ # Status code exists in response object
+ error_context = None
+ except requests.exceptions.HTTPError as errh:
+ error_context = "HTTP Error"
+ exception_text = str(errh)
+ except requests.exceptions.ProxyError as errp:
+ error_context = "Proxy Error"
+ exception_text = str(errp)
+ except requests.exceptions.ConnectionError as errc:
+ error_context = "Error Connecting"
+ exception_text = str(errc)
+ except requests.exceptions.Timeout as errt:
+ error_context = "Timeout Error"
+ exception_text = str(errt)
+ except requests.exceptions.RequestException as err:
+ error_context = "Unknown Error"
+ exception_text = str(err)
+
+ return response, error_context, exception_text
+
+
+def interpolate_string(input_object, username):
+ if isinstance(input_object, str):
+ return input_object.replace("{}", username)
+ elif isinstance(input_object, dict):
+ return {k: interpolate_string(v, username) for k, v in input_object.items()}
+ elif isinstance(input_object, list):
+ return [interpolate_string(i, username) for i in input_object]
+ return input_object
+
+
+def check_for_parameter(username):
+ """checks if {?} exists in the username
+ if exist it means that sherlock is looking for more multiple username"""
+ return "{?}" in username
+
+
+checksymbols = ["_", "-", "."]
+
+
+def multiple_usernames(username):
+ """replace the parameter with with symbols and return a list of usernames"""
+ allUsernames = []
+ for i in checksymbols:
+ allUsernames.append(username.replace("{?}", i))
+ return allUsernames
+
+
+def sherlock(
+ username: str,
+ site_data: dict[str, dict[str, str]],
+ query_notify: QueryNotify,
+ dump_response: bool = False,
+ proxy: Optional[str] = None,
+ timeout: int = 60,
+) -> dict[str, dict[str, str | QueryResult]]:
+ """Run Sherlock Analysis.
+
+ Checks for existence of username on various social media sites.
+
+ Keyword Arguments:
+ username -- String indicating username that report
+ should be created against.
+ site_data -- Dictionary containing all of the site data.
+ query_notify -- Object with base type of QueryNotify().
+ This will be used to notify the caller about
+ query results.
+ proxy -- String indicating the proxy URL
+ timeout -- Time in seconds to wait before timing out request.
+ Default is 60 seconds.
+
+ Return Value:
+ Dictionary containing results from report. Key of dictionary is the name
+ of the social network site, and the value is another dictionary with
+ the following keys:
+ url_main: URL of main site.
+ url_user: URL of user on site (if account exists).
+ status: QueryResult() object indicating results of test for
+ account existence.
+ http_status: HTTP status code of query which checked for existence on
+ site.
+ response_text: Text that came back from request. May be None if
+ there was an HTTP error when checking for existence.
+ """
+
+ # Notify caller that we are starting the query.
+ query_notify.start(username)
+
+ # Normal requests
+ underlying_session = requests.session()
+
+ # Limit number of workers to 20.
+ # This is probably vastly overkill.
+ if len(site_data) >= 20:
+ max_workers = 20
+ else:
+ max_workers = len(site_data)
+
+ # Create multi-threaded session for all requests.
+ session = SherlockFuturesSession(
+ max_workers=max_workers, session=underlying_session
+ )
+
+ # Results from analysis of all sites
+ results_total = {}
+
+ # First create futures for all requests. This allows for the requests to run in parallel
+ for social_network, net_info in site_data.items():
+ # Results from analysis of this specific site
+ results_site = {"url_main": net_info.get("urlMain")}
+
+ # Record URL of main site
+
+ # A user agent is needed because some sites don't return the correct
+ # information since they think that we are bots (Which we actually are...)
+ headers = {
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
+ }
+
+ if "headers" in net_info:
+ # Override/append any extra headers required by a given site.
+ headers.update(net_info["headers"])
+
+ # URL of user on site (if it exists)
+ url = interpolate_string(net_info["url"], username.replace(' ', '%20'))
+
+ # Don't make request if username is invalid for the site
+ regex_check = net_info.get("regexCheck")
+ if regex_check and re.search(regex_check, username) is None:
+ # No need to do the check at the site: this username is not allowed.
+ results_site["status"] = QueryResult(
+ username, social_network, url, QueryStatus.ILLEGAL
+ )
+ results_site["url_user"] = ""
+ results_site["http_status"] = ""
+ results_site["response_text"] = ""
+ query_notify.update(results_site["status"])
+ else:
+ # URL of user on site (if it exists)
+ results_site["url_user"] = url
+ url_probe = net_info.get("urlProbe")
+ request_method = net_info.get("request_method")
+ request_payload = net_info.get("request_payload")
+ request = None
+
+ if request_method is not None:
+ if request_method == "GET":
+ request = session.get
+ elif request_method == "HEAD":
+ request = session.head
+ elif request_method == "POST":
+ request = session.post
+ elif request_method == "PUT":
+ request = session.put
+ else:
+ raise RuntimeError(f"Unsupported request_method for {url}")
+
+ if request_payload is not None:
+ request_payload = interpolate_string(request_payload, username)
+
+ if url_probe is None:
+ # Probe URL is normal one seen by people out on the web.
+ url_probe = url
+ else:
+ # There is a special URL for probing existence separate
+ # from where the user profile normally can be found.
+ url_probe = interpolate_string(url_probe, username)
+
+ if request is None:
+ if net_info["errorType"] == "status_code":
+ # In most cases when we are detecting by status code,
+ # it is not necessary to get the entire body: we can
+ # detect fine with just the HEAD response.
+ request = session.head
+ else:
+ # Either this detect method needs the content associated
+ # with the GET response, or this specific website will
+ # not respond properly unless we request the whole page.
+ request = session.get
+
+ if net_info["errorType"] == "response_url":
+ # Site forwards request to a different URL if username not
+ # found. Disallow the redirect so we can capture the
+ # http status from the original URL request.
+ allow_redirects = False
+ else:
+ # Allow whatever redirect that the site wants to do.
+ # The final result of the request will be what is available.
+ allow_redirects = True
+
+ # This future starts running the request in a new thread, doesn't block the main thread
+ if proxy is not None:
+ proxies = {"http": proxy, "https": proxy}
+ future = request(
+ url=url_probe,
+ headers=headers,
+ proxies=proxies,
+ allow_redirects=allow_redirects,
+ timeout=timeout,
+ json=request_payload,
+ )
+ else:
+ future = request(
+ url=url_probe,
+ headers=headers,
+ allow_redirects=allow_redirects,
+ timeout=timeout,
+ json=request_payload,
+ )
+
+ # Store future in data for access later
+ net_info["request_future"] = future
+
+ # Add this site's results into final dictionary with all the other results.
+ results_total[social_network] = results_site
+
+ # Open the file containing account links
+ for social_network, net_info in site_data.items():
+ # Retrieve results again
+ results_site = results_total.get(social_network)
+
+ # Retrieve other site information again
+ url = results_site.get("url_user")
+ status = results_site.get("status")
+ if status is not None:
+ # We have already determined the user doesn't exist here
+ continue
+
+ # Get the expected error type
+ error_type = net_info["errorType"]
+ if isinstance(error_type, str):
+ error_type: list[str] = [error_type]
+
+ # Retrieve future and ensure it has finished
+ future = net_info["request_future"]
+ r, error_text, exception_text = get_response(
+ request_future=future, error_type=error_type, social_network=social_network
+ )
+
+ # Get response time for response of our request.
+ try:
+ response_time = r.elapsed
+ except AttributeError:
+ response_time = None
+
+ # Attempt to get request information
+ try:
+ http_status = r.status_code
+ except Exception:
+ http_status = "?"
+ try:
+ response_text = r.text.encode(r.encoding or "UTF-8")
+ except Exception:
+ response_text = ""
+
+ query_status = QueryStatus.UNKNOWN
+ error_context = None
+
+ # As WAFs advance and evolve, they will occasionally block Sherlock and
+ # lead to false positives and negatives. Fingerprints should be added
+ # here to filter results that fail to bypass WAFs. Fingerprints should
+ # be highly targetted. Comment at the end of each fingerprint to
+ # indicate target and date fingerprinted.
+ WAFHitMsgs = [
+ r'.loading-spinner{visibility:hidden}body.no-js .challenge-running{display:none}body.dark{background-color:#222;color:#d9d9d9}body.dark a{color:#fff}body.dark a:hover{color:#ee730a;text-decoration:underline}body.dark .lds-ring div{border-color:#999 transparent transparent}body.dark .font-red{color:#b20f03}body.dark', # 2024-05-13 Cloudflare
+ r'', # 2024-11-11 Cloudflare error page
+ r'AwsWafIntegration.forceRefreshToken', # 2024-11-11 Cloudfront (AWS)
+ r'{return l.onPageView}}),Object.defineProperty(r,"perimeterxIdentifiers",{enumerable:' # 2024-04-09 PerimeterX / Human Security
+ ]
+
+ if error_text is not None:
+ error_context = error_text
+
+ elif any(hitMsg in r.text for hitMsg in WAFHitMsgs):
+ query_status = QueryStatus.WAF
+
+ else:
+ if any(errtype not in ["message", "status_code", "response_url"] for errtype in error_type):
+ error_context = f"Unknown error type '{error_type}' for {social_network}"
+ query_status = QueryStatus.UNKNOWN
+ else:
+ if "message" in error_type:
+ # error_flag True denotes no error found in the HTML
+ # error_flag False denotes error found in the HTML
+ error_flag = True
+ errors = net_info.get("errorMsg")
+ # errors will hold the error message
+ # it can be string or list
+ # by isinstance method we can detect that
+ # and handle the case for strings as normal procedure
+ # and if its list we can iterate the errors
+ if isinstance(errors, str):
+ # Checks if the error message is in the HTML
+ # if error is present we will set flag to False
+ if errors in r.text:
+ error_flag = False
+ else:
+ # If it's list, it will iterate all the error message
+ for error in errors:
+ if error in r.text:
+ error_flag = False
+ break
+ if error_flag:
+ query_status = QueryStatus.CLAIMED
+ else:
+ query_status = QueryStatus.AVAILABLE
+
+ if "status_code" in error_type and query_status is not QueryStatus.AVAILABLE:
+ error_codes = net_info.get("errorCode")
+ query_status = QueryStatus.CLAIMED
+
+ # Type consistency, allowing for both singlets and lists in manifest
+ if isinstance(error_codes, int):
+ error_codes = [error_codes]
+
+ if error_codes is not None and r.status_code in error_codes:
+ query_status = QueryStatus.AVAILABLE
+ elif r.status_code >= 300 or r.status_code < 200:
+ query_status = QueryStatus.AVAILABLE
+
+ if "response_url" in error_type and query_status is not QueryStatus.AVAILABLE:
+ # For this detection method, we have turned off the redirect.
+ # So, there is no need to check the response URL: it will always
+ # match the request. Instead, we will ensure that the response
+ # code indicates that the request was successful (i.e. no 404, or
+ # forward to some odd redirect).
+ if 200 <= r.status_code < 300:
+ query_status = QueryStatus.CLAIMED
+ else:
+ query_status = QueryStatus.AVAILABLE
+
+ if dump_response:
+ print("+++++++++++++++++++++")
+ print(f"TARGET NAME : {social_network}")
+ print(f"USERNAME : {username}")
+ print(f"TARGET URL : {url}")
+ print(f"TEST METHOD : {error_type}")
+ try:
+ print(f"STATUS CODES : {net_info['errorCode']}")
+ except KeyError:
+ pass
+ print("Results...")
+ try:
+ print(f"RESPONSE CODE : {r.status_code}")
+ except Exception:
+ pass
+ try:
+ print(f"ERROR TEXT : {net_info['errorMsg']}")
+ except KeyError:
+ pass
+ print(">>>>> BEGIN RESPONSE TEXT")
+ try:
+ print(r.text)
+ except Exception:
+ pass
+ print("<<<<< END RESPONSE TEXT")
+ print("VERDICT : " + str(query_status))
+ print("+++++++++++++++++++++")
+
+ # Notify caller about results of query.
+ result: QueryResult = QueryResult(
+ username=username,
+ site_name=social_network,
+ site_url_user=url,
+ status=query_status,
+ query_time=response_time,
+ context=error_context,
+ )
+ query_notify.update(result)
+
+ # Save status of request
+ results_site["status"] = result
+
+ # Save results from request
+ results_site["http_status"] = http_status
+ results_site["response_text"] = response_text
+
+ # Add this site's results into final dictionary with all of the other results.
+ results_total[social_network] = results_site
+
+ return results_total
+
+
+def timeout_check(value):
+ """Check Timeout Argument.
+
+ Checks timeout for validity.
+
+ Keyword Arguments:
+ value -- Time in seconds to wait before timing out request.
+
+ Return Value:
+ Floating point number representing the time (in seconds) that should be
+ used for the timeout.
+
+ NOTE: Will raise an exception if the timeout in invalid.
+ """
+
+ float_value = float(value)
+
+ if float_value <= 0:
+ raise ArgumentTypeError(
+ f"Invalid timeout value: {value}. Timeout must be a positive number."
+ )
+
+ return float_value
+
+
+def handler(signal_received, frame):
+ """Exit gracefully without throwing errors
+
+ Source: https://www.devdungeon.com/content/python-catch-sigint-ctrl-c
+ """
+ sys.exit(0)
+
+
+def main():
+ parser = ArgumentParser(
+ formatter_class=RawDescriptionHelpFormatter,
+ description=f"{__longname__} (Version {__version__})",
+ )
+ parser.add_argument(
+ "--version",
+ action="version",
+ version=f"{__shortname__} v{__version__}",
+ help="Display version information and dependencies.",
+ )
+ parser.add_argument(
+ "--verbose",
+ "-v",
+ "-d",
+ "--debug",
+ action="store_true",
+ dest="verbose",
+ default=False,
+ help="Display extra debugging information and metrics.",
+ )
+ parser.add_argument(
+ "--folderoutput",
+ "-fo",
+ dest="folderoutput",
+ help="If using multiple usernames, the output of the results will be saved to this folder.",
+ )
+ parser.add_argument(
+ "--output",
+ "-o",
+ dest="output",
+ help="If using single username, the output of the result will be saved to this file.",
+ )
+ parser.add_argument(
+ "--csv",
+ action="store_true",
+ dest="csv",
+ default=False,
+ help="Create Comma-Separated Values (CSV) File.",
+ )
+ parser.add_argument(
+ "--xlsx",
+ action="store_true",
+ dest="xlsx",
+ default=False,
+ help="Create the standard file for the modern Microsoft Excel spreadsheet (xlsx).",
+ )
+ parser.add_argument(
+ "--site",
+ action="append",
+ metavar="SITE_NAME",
+ dest="site_list",
+ default=[],
+ help="Limit analysis to just the listed sites. Add multiple options to specify more than one site.",
+ )
+ parser.add_argument(
+ "--proxy",
+ "-p",
+ metavar="PROXY_URL",
+ action="store",
+ dest="proxy",
+ default=None,
+ help="Make requests over a proxy. e.g. socks5://127.0.0.1:1080",
+ )
+ parser.add_argument(
+ "--dump-response",
+ action="store_true",
+ dest="dump_response",
+ default=False,
+ help="Dump the HTTP response to stdout for targeted debugging.",
+ )
+ parser.add_argument(
+ "--json",
+ "-j",
+ metavar="JSON_FILE",
+ dest="json_file",
+ default=None,
+ help="Load data from a JSON file or an online, valid, JSON file. Upstream PR numbers also accepted.",
+ )
+ parser.add_argument(
+ "--timeout",
+ action="store",
+ metavar="TIMEOUT",
+ dest="timeout",
+ type=timeout_check,
+ default=60,
+ help="Time (in seconds) to wait for response to requests (Default: 60)",
+ )
+ parser.add_argument(
+ "--print-all",
+ action="store_true",
+ dest="print_all",
+ default=False,
+ help="Output sites where the username was not found.",
+ )
+ parser.add_argument(
+ "--print-found",
+ action="store_true",
+ dest="print_found",
+ default=True,
+ help="Output sites where the username was found (also if exported as file).",
+ )
+ parser.add_argument(
+ "--no-color",
+ action="store_true",
+ dest="no_color",
+ default=False,
+ help="Don't color terminal output",
+ )
+ parser.add_argument(
+ "username",
+ nargs="+",
+ metavar="USERNAMES",
+ action="store",
+ help="One or more usernames to check with social networks. Check similar usernames using {?} (replace to '_', '-', '.').",
+ )
+ parser.add_argument(
+ "--browse",
+ "-b",
+ action="store_true",
+ dest="browse",
+ default=False,
+ help="Browse to all results on default browser.",
+ )
+
+ parser.add_argument(
+ "--local",
+ "-l",
+ action="store_true",
+ default=False,
+ help="Force the use of the local data.json file.",
+ )
+
+ parser.add_argument(
+ "--nsfw",
+ action="store_true",
+ default=False,
+ help="Include checking of NSFW sites from default list.",
+ )
+
+ # TODO deprecated in favor of --txt, retained for workflow compatibility, to be removed
+ # in future release
+ parser.add_argument(
+ "--no-txt",
+ action="store_true",
+ dest="no_txt",
+ default=False,
+ help="Disable creation of a txt file - WILL BE DEPRECATED",
+ )
+
+ parser.add_argument(
+ "--txt",
+ action="store_true",
+ dest="output_txt",
+ default=False,
+ help="Enable creation of a txt file",
+ )
+
+ parser.add_argument(
+ "--ignore-exclusions",
+ action="store_true",
+ dest="ignore_exclusions",
+ default=False,
+ help="Ignore upstream exclusions (may return more false positives)",
+ )
+
+ args = parser.parse_args()
+
+ # If the user presses CTRL-C, exit gracefully without throwing errors
+ signal.signal(signal.SIGINT, handler)
+
+ # Check for newer version of Sherlock. If it exists, let the user know about it
+ try:
+ latest_release_raw = requests.get(forge_api_latest_release, timeout=10).text
+ latest_release_json = json_loads(latest_release_raw)
+ latest_remote_tag = latest_release_json["tag_name"]
+
+ if latest_remote_tag[1:] != __version__:
+ print(
+ f"Update available! {__version__} --> {latest_remote_tag[1:]}"
+ f"\n{latest_release_json['html_url']}"
+ )
+
+ except Exception as error:
+ print(f"A problem occurred while checking for an update: {error}")
+
+ # Make prompts
+ if args.proxy is not None:
+ print("Using the proxy: " + args.proxy)
+
+ if args.no_color:
+ # Disable color output.
+ init(strip=True, convert=False)
+ else:
+ # Enable color output.
+ init(autoreset=True)
+
+ # Check if both output methods are entered as input.
+ if args.output is not None and args.folderoutput is not None:
+ print("You can only use one of the output methods.")
+ sys.exit(1)
+
+ # Check validity for single username output.
+ if args.output is not None and len(args.username) != 1:
+ print("You can only use --output with a single username")
+ sys.exit(1)
+
+ # Create object with all information about sites we are aware of.
+ try:
+ if args.local:
+ sites = SitesInformation(
+ os.path.join(os.path.dirname(__file__), "resources/data.json"),
+ honor_exclusions=False,
+ )
+ else:
+ json_file_location = args.json_file
+ if args.json_file:
+ # If --json parameter is a number, interpret it as a pull request number
+ if args.json_file.isnumeric():
+ pull_number = args.json_file
+ pull_url = f"https://api.github.com/repos/sherlock-project/sherlock/pulls/{pull_number}"
+ pull_request_raw = requests.get(pull_url, timeout=10).text
+ pull_request_json = json_loads(pull_request_raw)
+
+ # Check if it's a valid pull request
+ if "message" in pull_request_json:
+ print(f"ERROR: Pull request #{pull_number} not found.")
+ sys.exit(1)
+
+ head_commit_sha = pull_request_json["head"]["sha"]
+ json_file_location = f"https://raw.githubusercontent.com/sherlock-project/sherlock/{head_commit_sha}/sherlock_project/resources/data.json"
+
+ sites = SitesInformation(
+ data_file_path=json_file_location,
+ honor_exclusions=not args.ignore_exclusions,
+ do_not_exclude=args.site_list,
+ )
+ except Exception as error:
+ print(f"ERROR: {error}")
+ sys.exit(1)
+
+ if not args.nsfw:
+ sites.remove_nsfw_sites(do_not_remove=args.site_list)
+
+ # Create original dictionary from SitesInformation() object.
+ # Eventually, the rest of the code will be updated to use the new object
+ # directly, but this will glue the two pieces together.
+ site_data_all = {site.name: site.information for site in sites}
+ if args.site_list == []:
+ # Not desired to look at a sub-set of sites
+ site_data = site_data_all
+ else:
+ # User desires to selectively run queries on a sub-set of the site list.
+ # Make sure that the sites are supported & build up pruned site database.
+ site_data = {}
+ site_missing = []
+ for site in args.site_list:
+ counter = 0
+ for existing_site in site_data_all:
+ if site.lower() == existing_site.lower():
+ site_data[existing_site] = site_data_all[existing_site]
+ counter += 1
+ if counter == 0:
+ # Build up list of sites not supported for future error message.
+ site_missing.append(f"'{site}'")
+
+ if site_missing:
+ print(f"Error: Desired sites not found: {', '.join(site_missing)}.")
+
+ if not site_data:
+ sys.exit(1)
+
+ # Create notify object for query results.
+ query_notify = QueryNotifyPrint(
+ result=None, verbose=args.verbose, print_all=args.print_all, browse=args.browse
+ )
+
+ # Run report on all specified users.
+ all_usernames = []
+ for username in args.username:
+ if check_for_parameter(username):
+ for name in multiple_usernames(username):
+ all_usernames.append(name)
+ else:
+ all_usernames.append(username)
+ for username in all_usernames:
+ results = sherlock(
+ username,
+ site_data,
+ query_notify,
+ dump_response=args.dump_response,
+ proxy=args.proxy,
+ timeout=args.timeout,
+ )
+
+ if args.output:
+ result_file = args.output
+ elif args.folderoutput:
+ # The usernames results should be stored in a targeted folder.
+ # If the folder doesn't exist, create it first
+ os.makedirs(args.folderoutput, exist_ok=True)
+ result_file = os.path.join(args.folderoutput, f"{username}.txt")
+ else:
+ result_file = f"{username}.txt"
+
+ if args.output_txt:
+ with open(result_file, "w", encoding="utf-8") as file:
+ exists_counter = 0
+ for website_name in results:
+ dictionary = results[website_name]
+ if dictionary.get("status").status == QueryStatus.CLAIMED:
+ exists_counter += 1
+ file.write(dictionary["url_user"] + "\n")
+ file.write(f"Total Websites Username Detected On : {exists_counter}\n")
+
+ if args.csv:
+ result_file = f"{username}.csv"
+ if args.folderoutput:
+ # The usernames results should be stored in a targeted folder.
+ # If the folder doesn't exist, create it first
+ os.makedirs(args.folderoutput, exist_ok=True)
+ result_file = os.path.join(args.folderoutput, result_file)
+
+ with open(result_file, "w", newline="", encoding="utf-8") as csv_report:
+ writer = csv.writer(csv_report)
+ writer.writerow(
+ [
+ "username",
+ "name",
+ "url_main",
+ "url_user",
+ "exists",
+ "http_status",
+ "response_time_s",
+ ]
+ )
+ for site in results:
+ if (
+ args.print_found
+ and not args.print_all
+ and results[site]["status"].status != QueryStatus.CLAIMED
+ ):
+ continue
+
+ response_time_s = results[site]["status"].query_time
+ if response_time_s is None:
+ response_time_s = ""
+ writer.writerow(
+ [
+ username,
+ site,
+ results[site]["url_main"],
+ results[site]["url_user"],
+ str(results[site]["status"].status),
+ results[site]["http_status"],
+ response_time_s,
+ ]
+ )
+ if args.xlsx:
+ usernames = []
+ names = []
+ url_main = []
+ url_user = []
+ exists = []
+ http_status = []
+ response_time_s = []
+
+ for site in results:
+ if (
+ args.print_found
+ and not args.print_all
+ and results[site]["status"].status != QueryStatus.CLAIMED
+ ):
+ continue
+
+ if response_time_s is None:
+ response_time_s.append("")
+ else:
+ response_time_s.append(results[site]["status"].query_time)
+ usernames.append(username)
+ names.append(site)
+ url_main.append(results[site]["url_main"])
+ url_user.append(results[site]["url_user"])
+ exists.append(str(results[site]["status"].status))
+ http_status.append(results[site]["http_status"])
+
+ DataFrame = pd.DataFrame(
+ {
+ "username": usernames,
+ "name": names,
+ "url_main": [f'=HYPERLINK(\"{u}\")' for u in url_main],
+ "url_user": [f'=HYPERLINK(\"{u}\")' for u in url_user],
+ "exists": exists,
+ "http_status": http_status,
+ "response_time_s": response_time_s,
+ }
+ )
+ DataFrame.to_excel(f"{username}.xlsx", sheet_name="sheet1", index=False)
+
+ print()
+ query_notify.finish()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/sherlock/sherlock_project/sites.py b/sherlock/sherlock_project/sites.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f9191e52069a2d2bef41e60ac61b4a65a6f666
--- /dev/null
+++ b/sherlock/sherlock_project/sites.py
@@ -0,0 +1,265 @@
+"""Sherlock Sites Information Module
+
+This module supports storing information about websites.
+This is the raw data that will be used to search for usernames.
+"""
+import json
+import requests
+import secrets
+
+
+MANIFEST_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.json"
+EXCLUSIONS_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/refs/heads/exclusions/false_positive_exclusions.txt"
+
+class SiteInformation:
+ def __init__(self, name, url_home, url_username_format, username_claimed,
+ information, is_nsfw, username_unclaimed=secrets.token_urlsafe(10)):
+ """Create Site Information Object.
+
+ Contains information about a specific website.
+
+ Keyword Arguments:
+ self -- This object.
+ name -- String which identifies site.
+ url_home -- String containing URL for home of site.
+ url_username_format -- String containing URL for Username format
+ on site.
+ NOTE: The string should contain the
+ token "{}" where the username should
+ be substituted. For example, a string
+ of "https://somesite.com/users/{}"
+ indicates that the individual
+ usernames would show up under the
+ "https://somesite.com/users/" area of
+ the website.
+ username_claimed -- String containing username which is known
+ to be claimed on website.
+ username_unclaimed -- String containing username which is known
+ to be unclaimed on website.
+ information -- Dictionary containing all known information
+ about website.
+ NOTE: Custom information about how to
+ actually detect the existence of the
+ username will be included in this
+ dictionary. This information will
+ be needed by the detection method,
+ but it is only recorded in this
+ object for future use.
+ is_nsfw -- Boolean indicating if site is Not Safe For Work.
+
+ Return Value:
+ Nothing.
+ """
+
+ self.name = name
+ self.url_home = url_home
+ self.url_username_format = url_username_format
+
+ self.username_claimed = username_claimed
+ self.username_unclaimed = secrets.token_urlsafe(32)
+ self.information = information
+ self.is_nsfw = is_nsfw
+
+ return
+
+ def __str__(self):
+ """Convert Object To String.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Nicely formatted string to get information about this object.
+ """
+
+ return f"{self.name} ({self.url_home})"
+
+
+class SitesInformation:
+ def __init__(
+ self,
+ data_file_path: str|None = None,
+ honor_exclusions: bool = True,
+ do_not_exclude: list[str] = [],
+ ):
+ """Create Sites Information Object.
+
+ Contains information about all supported websites.
+
+ Keyword Arguments:
+ self -- This object.
+ data_file_path -- String which indicates path to data file.
+ The file name must end in ".json".
+
+ There are 3 possible formats:
+ * Absolute File Format
+ For example, "c:/stuff/data.json".
+ * Relative File Format
+ The current working directory is used
+ as the context.
+ For example, "data.json".
+ * URL Format
+ For example,
+ "https://example.com/data.json", or
+ "http://example.com/data.json".
+
+ An exception will be thrown if the path
+ to the data file is not in the expected
+ format, or if there was any problem loading
+ the file.
+
+ If this option is not specified, then a
+ default site list will be used.
+
+ Return Value:
+ Nothing.
+ """
+
+ if not data_file_path:
+ # The default data file is the live data.json which is in the GitHub repo. The reason why we are using
+ # this instead of the local one is so that the user has the most up-to-date data. This prevents
+ # users from creating issue about false positives which has already been fixed or having outdated data
+ data_file_path = MANIFEST_URL
+
+ # Ensure that specified data file has correct extension.
+ if not data_file_path.lower().endswith(".json"):
+ raise FileNotFoundError(f"Incorrect JSON file extension for data file '{data_file_path}'.")
+
+ # if "http://" == data_file_path[:7].lower() or "https://" == data_file_path[:8].lower():
+ if data_file_path.lower().startswith("http"):
+ # Reference is to a URL.
+ try:
+ response = requests.get(url=data_file_path, timeout=30)
+ except Exception as error:
+ raise FileNotFoundError(
+ f"Problem while attempting to access data file URL '{data_file_path}': {error}"
+ )
+
+ if response.status_code != 200:
+ raise FileNotFoundError(f"Bad response while accessing "
+ f"data file URL '{data_file_path}'."
+ )
+ try:
+ site_data = response.json()
+ except Exception as error:
+ raise ValueError(
+ f"Problem parsing json contents at '{data_file_path}': {error}."
+ )
+
+ else:
+ # Reference is to a file.
+ try:
+ with open(data_file_path, "r", encoding="utf-8") as file:
+ try:
+ site_data = json.load(file)
+ except Exception as error:
+ raise ValueError(
+ f"Problem parsing json contents at '{data_file_path}': {error}."
+ )
+
+ except FileNotFoundError:
+ raise FileNotFoundError(f"Problem while attempting to access "
+ f"data file '{data_file_path}'."
+ )
+
+ site_data.pop('$schema', None)
+
+ if honor_exclusions:
+ try:
+ response = requests.get(url=EXCLUSIONS_URL, timeout=10)
+ if response.status_code == 200:
+ exclusions = response.text.splitlines()
+ exclusions = [exclusion.strip() for exclusion in exclusions]
+
+ for site in do_not_exclude:
+ if site in exclusions:
+ exclusions.remove(site)
+
+ for exclusion in exclusions:
+ try:
+ site_data.pop(exclusion, None)
+ except KeyError:
+ pass
+
+ except Exception:
+ # If there was any problem loading the exclusions, just continue without them
+ print("Warning: Could not load exclusions, continuing without them.")
+ honor_exclusions = False
+
+ self.sites = {}
+
+ # Add all site information from the json file to internal site list.
+ for site_name in site_data:
+ try:
+
+ self.sites[site_name] = \
+ SiteInformation(site_name,
+ site_data[site_name]["urlMain"],
+ site_data[site_name]["url"],
+ site_data[site_name]["username_claimed"],
+ site_data[site_name],
+ site_data[site_name].get("isNSFW",False)
+
+ )
+ except KeyError as error:
+ raise ValueError(
+ f"Problem parsing json contents at '{data_file_path}': Missing attribute {error}."
+ )
+ except TypeError:
+ print(f"Encountered TypeError parsing json contents for target '{site_name}' at {data_file_path}\nSkipping target.\n")
+
+ return
+
+ def remove_nsfw_sites(self, do_not_remove: list = []):
+ """
+ Remove NSFW sites from the sites, if isNSFW flag is true for site
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ None
+ """
+ sites = {}
+ do_not_remove = [site.casefold() for site in do_not_remove]
+ for site in self.sites:
+ if self.sites[site].is_nsfw and site.casefold() not in do_not_remove:
+ continue
+ sites[site] = self.sites[site]
+ self.sites = sites
+
+ def site_name_list(self):
+ """Get Site Name List.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ List of strings containing names of sites.
+ """
+
+ return sorted([site.name for site in self], key=str.lower)
+
+ def __iter__(self):
+ """Iterator For Object.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Iterator for sites object.
+ """
+
+ for site_name in self.sites:
+ yield self.sites[site_name]
+
+ def __len__(self):
+ """Length For Object.
+
+ Keyword Arguments:
+ self -- This object.
+
+ Return Value:
+ Length of sites object.
+ """
+ return len(self.sites)
diff --git a/sherlock/tests/conftest.py b/sherlock/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..27b3e77f56837dfbc4232a186deaf36833efcc3e
--- /dev/null
+++ b/sherlock/tests/conftest.py
@@ -0,0 +1,51 @@
+import os
+import json
+import urllib
+import pytest
+from sherlock_project.sites import SitesInformation
+
+def fetch_local_manifest(honor_exclusions: bool = True) -> dict[str, dict[str, str]]:
+ sites_obj = SitesInformation(data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock_project/resources/data.json"), honor_exclusions=honor_exclusions)
+ sites_iterable: dict[str, dict[str, str]] = {site.name: site.information for site in sites_obj}
+ return sites_iterable
+
+@pytest.fixture()
+def sites_obj():
+ sites_obj = SitesInformation(data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock_project/resources/data.json"))
+ yield sites_obj
+
+@pytest.fixture(scope="session")
+def sites_info():
+ yield fetch_local_manifest()
+
+@pytest.fixture(scope="session")
+def remote_schema():
+ schema_url: str = 'https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.schema.json'
+ with urllib.request.urlopen(schema_url) as remoteschema:
+ schemadat = json.load(remoteschema)
+ yield schemadat
+
+def pytest_addoption(parser):
+ parser.addoption(
+ "--chunked-sites",
+ action="store",
+ default=None,
+ help="For tests utilizing chunked sites, include only the (comma-separated) site(s) specified.",
+ )
+
+def pytest_generate_tests(metafunc):
+ if "chunked_sites" in metafunc.fixturenames:
+ sites_info = fetch_local_manifest(honor_exclusions=False)
+
+ # Ingest and apply site selections
+ site_filter: str | None = metafunc.config.getoption("--chunked-sites")
+ if site_filter:
+ selected_sites: list[str] = [site.strip() for site in site_filter.split(",")]
+ sites_info = {
+ site: data for site, data in sites_info.items()
+ if site in selected_sites
+ }
+
+ params = [{name: data} for name, data in sites_info.items()]
+ ids = list(sites_info.keys())
+ metafunc.parametrize("chunked_sites", params, ids=ids)
diff --git a/sherlock/tests/few_test_basic.py b/sherlock/tests/few_test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef8f3823bf731addc2c683a3046a20dbd04e74ed
--- /dev/null
+++ b/sherlock/tests/few_test_basic.py
@@ -0,0 +1,7 @@
+import sherlock_project
+
+#from sherlock.sites import SitesInformation
+#local_manifest = data_file_path=os.path.join(os.path.dirname(__file__), "../sherlock/resources/data.json")
+
+def test_username_via_message():
+ sherlock_project.__main__("--version")
diff --git a/sherlock/tests/sherlock_interactives.py b/sherlock/tests/sherlock_interactives.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e20c6907fc3a282b71ff58ed2693b2fd206e730
--- /dev/null
+++ b/sherlock/tests/sherlock_interactives.py
@@ -0,0 +1,38 @@
+import os
+import platform
+import re
+import subprocess
+
+class Interactives:
+ def run_cli(args:str = "") -> str:
+ """Pass arguments to Sherlock as a normal user on the command line"""
+ # Adapt for platform differences (Windows likes to be special)
+ if platform.system() == "Windows":
+ command:str = f"py -m sherlock_project {args}"
+ else:
+ command:str = f"sherlock {args}"
+
+ proc_out:str = ""
+ try:
+ proc_out = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
+ return proc_out.decode()
+ except subprocess.CalledProcessError as e:
+ raise InteractivesSubprocessError(e.output.decode())
+
+
+ def walk_sherlock_for_files_with(pattern: str) -> list[str]:
+ """Check all files within the Sherlock package for matching patterns"""
+ pattern:re.Pattern = re.compile(pattern)
+ matching_files:list[str] = []
+ for root, dirs, files in os.walk("sherlock_project"):
+ for file in files:
+ file_path = os.path.join(root,file)
+ if "__pycache__" in file_path:
+ continue
+ with open(file_path, 'r', errors='ignore') as f:
+ if pattern.search(f.read()):
+ matching_files.append(file_path)
+ return matching_files
+
+class InteractivesSubprocessError(Exception):
+ pass
diff --git a/sherlock/tests/test_manifest.py b/sherlock/tests/test_manifest.py
new file mode 100644
index 0000000000000000000000000000000000000000..a055b989af5fe1fa000c214607e7c16b77a66560
--- /dev/null
+++ b/sherlock/tests/test_manifest.py
@@ -0,0 +1,39 @@
+import os
+import json
+import pytest
+from jsonschema import validate
+
+def test_validate_manifest_against_local_schema():
+ """Ensures that the manifest matches the local schema, for situations where the schema is being changed."""
+ json_relative: str = '../sherlock_project/resources/data.json'
+ schema_relative: str = '../sherlock_project/resources/data.schema.json'
+
+ json_path: str = os.path.join(os.path.dirname(__file__), json_relative)
+ schema_path: str = os.path.join(os.path.dirname(__file__), schema_relative)
+
+ with open(json_path, 'r') as f:
+ jsondat = json.load(f)
+ with open(schema_path, 'r') as f:
+ schemadat = json.load(f)
+
+ validate(instance=jsondat, schema=schemadat)
+
+
+@pytest.mark.online
+def test_validate_manifest_against_remote_schema(remote_schema):
+ """Ensures that the manifest matches the remote schema, so as to not unexpectedly break clients."""
+ json_relative: str = '../sherlock_project/resources/data.json'
+ json_path: str = os.path.join(os.path.dirname(__file__), json_relative)
+
+ with open(json_path, 'r') as f:
+ jsondat = json.load(f)
+
+ validate(instance=jsondat, schema=remote_schema)
+
+# Ensure that the expected values are beind returned by the site list
+@pytest.mark.parametrize("target_name,target_expected_err_type", [
+ ('GitHub', 'status_code'),
+ ('GitLab', 'message'),
+])
+def test_site_list_iterability (sites_info, target_name, target_expected_err_type):
+ assert sites_info[target_name]['errorType'] == target_expected_err_type
diff --git a/sherlock/tests/test_probes.py b/sherlock/tests/test_probes.py
new file mode 100644
index 0000000000000000000000000000000000000000..86f7199e795bf7d5d53b8a562080d928753570de
--- /dev/null
+++ b/sherlock/tests/test_probes.py
@@ -0,0 +1,105 @@
+import pytest
+import random
+import string
+import re
+from sherlock_project.sherlock import sherlock
+from sherlock_project.notify import QueryNotify
+from sherlock_project.result import QueryStatus
+#from sherlock_interactives import Interactives
+
+
+def simple_query(sites_info: dict, site: str, username: str) -> QueryStatus:
+ query_notify = QueryNotify()
+ site_data: dict = {}
+ site_data[site] = sites_info[site]
+ return sherlock(
+ username=username,
+ site_data=site_data,
+ query_notify=query_notify,
+ )[site]['status'].status
+
+
+@pytest.mark.online
+class TestLiveTargets:
+ """Actively test probes against live and trusted targets"""
+ # Known positives should only use sites trusted to be reliable and unchanging
+ @pytest.mark.parametrize('site,username',[
+ ('GitLab', 'ppfeister'),
+ ('AllMyLinks', 'blue'),
+ ])
+ def test_known_positives_via_message(self, sites_info, site, username):
+ assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
+
+
+ # Known positives should only use sites trusted to be reliable and unchanging
+ @pytest.mark.parametrize('site,username',[
+ ('GitHub', 'ppfeister'),
+ ('GitHub', 'sherlock-project'),
+ ('Docker Hub', 'ppfeister'),
+ ('Docker Hub', 'sherlock'),
+ ])
+ def test_known_positives_via_status_code(self, sites_info, site, username):
+ assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
+
+
+ # Known positives should only use sites trusted to be reliable and unchanging
+ @pytest.mark.parametrize('site,username',[
+ ('Keybase', 'blue'),
+ ('devRant', 'blue'),
+ ])
+ def test_known_positives_via_response_url(self, sites_info, site, username):
+ assert simple_query(sites_info=sites_info, site=site, username=username) is QueryStatus.CLAIMED
+
+
+ # Randomly generate usernames of high length and test for positive availability
+ # Randomly generated usernames should be simple alnum for simplicity and high
+ # compatibility. Several attempts may be made ~just in case~ a real username is
+ # generated.
+ @pytest.mark.parametrize('site,random_len',[
+ ('GitLab', 255),
+ ('Codecademy', 30)
+ ])
+ def test_likely_negatives_via_message(self, sites_info, site, random_len):
+ num_attempts: int = 3
+ attempted_usernames: list[str] = []
+ status: QueryStatus = QueryStatus.CLAIMED
+ for i in range(num_attempts):
+ acceptable_types = string.ascii_letters + string.digits
+ random_handle = ''.join(random.choice(acceptable_types) for _ in range (random_len))
+ attempted_usernames.append(random_handle)
+ status = simple_query(sites_info=sites_info, site=site, username=random_handle)
+ if status is QueryStatus.AVAILABLE:
+ break
+ assert status is QueryStatus.AVAILABLE, f"Could not validate available username after {num_attempts} attempts with randomly generated usernames {attempted_usernames}."
+
+
+ # Randomly generate usernames of high length and test for positive availability
+ # Randomly generated usernames should be simple alnum for simplicity and high
+ # compatibility. Several attempts may be made ~just in case~ a real username is
+ # generated.
+ @pytest.mark.parametrize('site,random_len',[
+ ('GitHub', 39),
+ ('Docker Hub', 30)
+ ])
+ def test_likely_negatives_via_status_code(self, sites_info, site, random_len):
+ num_attempts: int = 3
+ attempted_usernames: list[str] = []
+ status: QueryStatus = QueryStatus.CLAIMED
+ for i in range(num_attempts):
+ acceptable_types = string.ascii_letters + string.digits
+ random_handle = ''.join(random.choice(acceptable_types) for _ in range (random_len))
+ attempted_usernames.append(random_handle)
+ status = simple_query(sites_info=sites_info, site=site, username=random_handle)
+ if status is QueryStatus.AVAILABLE:
+ break
+ assert status is QueryStatus.AVAILABLE, f"Could not validate available username after {num_attempts} attempts with randomly generated usernames {attempted_usernames}."
+
+
+def test_username_illegal_regex(sites_info):
+ site: str = 'BitBucket'
+ invalid_handle: str = '*#$Y&*JRE'
+ pattern = re.compile(sites_info[site]['regexCheck'])
+ # Ensure that the username actually fails regex before testing sherlock
+ assert pattern.match(invalid_handle) is None
+ assert simple_query(sites_info=sites_info, site=site, username=invalid_handle) is QueryStatus.ILLEGAL
+
diff --git a/sherlock/tests/test_ux.py b/sherlock/tests/test_ux.py
new file mode 100644
index 0000000000000000000000000000000000000000..f52029bac9280bfa4b5e26c66c27282d6e9091e6
--- /dev/null
+++ b/sherlock/tests/test_ux.py
@@ -0,0 +1,43 @@
+import pytest
+from sherlock_project import sherlock
+from sherlock_interactives import Interactives
+from sherlock_interactives import InteractivesSubprocessError
+
+def test_remove_nsfw(sites_obj):
+ nsfw_target: str = 'Pornhub'
+ assert nsfw_target in {site.name: site.information for site in sites_obj}
+ sites_obj.remove_nsfw_sites()
+ assert nsfw_target not in {site.name: site.information for site in sites_obj}
+
+
+# Parametrized sites should *not* include Motherless, which is acting as the control
+@pytest.mark.parametrize('nsfwsites', [
+ ['Pornhub'],
+ ['Pornhub', 'Xvideos'],
+])
+def test_nsfw_explicit_selection(sites_obj, nsfwsites):
+ for site in nsfwsites:
+ assert site in {site.name: site.information for site in sites_obj}
+ sites_obj.remove_nsfw_sites(do_not_remove=nsfwsites)
+ for site in nsfwsites:
+ assert site in {site.name: site.information for site in sites_obj}
+ assert 'Motherless' not in {site.name: site.information for site in sites_obj}
+
+def test_wildcard_username_expansion():
+ assert sherlock.check_for_parameter('test{?}test') is True
+ assert sherlock.check_for_parameter('test{.}test') is False
+ assert sherlock.check_for_parameter('test{}test') is False
+ assert sherlock.check_for_parameter('testtest') is False
+ assert sherlock.check_for_parameter('test{?test') is False
+ assert sherlock.check_for_parameter('test?}test') is False
+ assert sherlock.multiple_usernames('test{?}test') == ["test_test" , "test-test" , "test.test"]
+
+
+@pytest.mark.parametrize('cliargs', [
+ '',
+ '--site urghrtuight --egiotr',
+ '--',
+])
+def test_no_usernames_provided(cliargs):
+ with pytest.raises(InteractivesSubprocessError, match=r"error: the following arguments are required: USERNAMES"):
+ Interactives.run_cli(cliargs)
diff --git a/sherlock/tests/test_validate_targets.py b/sherlock/tests/test_validate_targets.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e72f99d5eebf66648179e94214a9ba00865faf5
--- /dev/null
+++ b/sherlock/tests/test_validate_targets.py
@@ -0,0 +1,99 @@
+import pytest
+import re
+import rstr
+
+from sherlock_project.sherlock import sherlock
+from sherlock_project.notify import QueryNotify
+from sherlock_project.result import QueryResult, QueryStatus
+
+
+FALSE_POSITIVE_ATTEMPTS: int = 2 # Since the usernames are randomly generated, it's POSSIBLE that a real username can be hit
+FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND: int = 15 # If a pattern uses quantifiers such as `+` `*` or `{n,}`, limit the upper bound (0 to disable)
+FALSE_POSITIVE_DEFAULT_PATTERN: str = r'^[a-zA-Z0-9]{7,20}$' # Used in absence of a regexCheck entry
+
+
+def set_pattern_upper_bound(pattern: str, upper_bound: int = FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND) -> str:
+ """Set upper bound for regex patterns that use quantifiers such as `+` `*` or `{n,}`."""
+ def replace_upper_bound(match: re.Match) -> str: # type: ignore
+ lower_bound: int = int(match.group(1)) if match.group(1) else 0 # type: ignore
+ upper_bound = upper_bound if lower_bound < upper_bound else lower_bound # type: ignore # noqa: F823
+ return f'{{{lower_bound},{upper_bound}}}'
+
+ pattern = re.sub(r'(? QueryStatus:
+ """Check if a site is likely to produce false positives."""
+ status: QueryStatus = QueryStatus.UNKNOWN
+
+ for _ in range(FALSE_POSITIVE_ATTEMPTS):
+ query_notify: QueryNotify = QueryNotify()
+ username: str = rstr.xeger(pattern)
+
+ result: QueryResult | str = sherlock(
+ username=username,
+ site_data=sites_info,
+ query_notify=query_notify,
+ )[site]['status']
+
+ if not hasattr(result, 'status'):
+ raise TypeError(f"Result for site {site} does not have 'status' attribute. Actual result: {result}")
+ if type(result.status) is not QueryStatus: # type: ignore
+ raise TypeError(f"Result status for site {site} is not of type QueryStatus. Actual type: {type(result.status)}") # type: ignore
+ status = result.status # type: ignore
+
+ if status in (QueryStatus.AVAILABLE, QueryStatus.WAF):
+ return status
+
+ return status
+
+
+def false_negative_check(sites_info: dict[str, dict[str, str]], site: str) -> QueryStatus:
+ """Check if a site is likely to produce false negatives."""
+ status: QueryStatus = QueryStatus.UNKNOWN
+ query_notify: QueryNotify = QueryNotify()
+
+ result: QueryResult | str = sherlock(
+ username=sites_info[site]['username_claimed'],
+ site_data=sites_info,
+ query_notify=query_notify,
+ )[site]['status']
+
+ if not hasattr(result, 'status'):
+ raise TypeError(f"Result for site {site} does not have 'status' attribute. Actual result: {result}")
+ if type(result.status) is not QueryStatus: # type: ignore
+ raise TypeError(f"Result status for site {site} is not of type QueryStatus. Actual type: {type(result.status)}") # type: ignore
+ status = result.status # type: ignore
+
+ return status
+
+@pytest.mark.validate_targets
+@pytest.mark.online
+class Test_All_Targets:
+
+ @pytest.mark.validate_targets_fp
+ def test_false_pos(self, chunked_sites: dict[str, dict[str, str]]):
+ """Iterate through all sites in the manifest to discover possible false-positive inducting targets."""
+ pattern: str
+ for site in chunked_sites:
+ try:
+ pattern = chunked_sites[site]['regexCheck']
+ except KeyError:
+ pattern = FALSE_POSITIVE_DEFAULT_PATTERN
+
+ if FALSE_POSITIVE_QUANTIFIER_UPPER_BOUND > 0:
+ pattern = set_pattern_upper_bound(pattern)
+
+ result: QueryStatus = false_positive_check(chunked_sites, site, pattern)
+ assert result is QueryStatus.AVAILABLE, f"{site} produced false positive with pattern {pattern}, result was {result}"
+
+ @pytest.mark.validate_targets_fn
+ def test_false_neg(self, chunked_sites: dict[str, dict[str, str]]):
+ """Iterate through all sites in the manifest to discover possible false-negative inducting targets."""
+ for site in chunked_sites:
+ result: QueryStatus = false_negative_check(chunked_sites, site)
+ assert result is QueryStatus.CLAIMED, f"{site} produced false negative, result was {result}"
+
diff --git a/sherlock/tests/test_version.py b/sherlock/tests/test_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..7406906597047a025493ea1d15f3d2898ffeeb2e
--- /dev/null
+++ b/sherlock/tests/test_version.py
@@ -0,0 +1,16 @@
+import os
+from sherlock_interactives import Interactives
+import sherlock_project
+
+def test_versioning() -> None:
+ # Ensure __version__ matches version presented to the user
+ assert sherlock_project.__version__ in Interactives.run_cli("--version")
+ # Ensure __init__ is single source of truth for __version__ in package
+ # Temporarily allows sherlock.py so as to not trigger early upgrades
+ found:list = Interactives.walk_sherlock_for_files_with(r'__version__ *= *')
+ expected:list = [
+ # Normalization is REQUIRED for Windows ( / vs \ )
+ os.path.normpath("sherlock_project/__init__.py"),
+ ]
+ # Sorting is REQUIRED for Mac
+ assert sorted(found) == sorted(expected)
diff --git a/sherlock/tox.ini b/sherlock/tox.ini
new file mode 100644
index 0000000000000000000000000000000000000000..3f0e8b7ab7c4285bf32c9d5c00513605f21f1914
--- /dev/null
+++ b/sherlock/tox.ini
@@ -0,0 +1,42 @@
+[tox]
+requires =
+ tox >= 3
+envlist =
+ lint
+ py313
+ py312
+ py311
+ py310
+
+[testenv]
+description = Attempt to build and install the package
+deps =
+ coverage
+ jsonschema
+ pytest
+ rstr
+allowlist_externals = coverage
+commands =
+ coverage run --source=sherlock_project --module pytest -v
+ coverage report --show-missing
+
+[testenv:offline]
+deps =
+ jsonschema
+ pytest
+commands =
+ pytest -v -m "not online"
+
+[testenv:lint]
+description = Lint with Ruff
+deps =
+ ruff
+commands =
+ ruff check
+
+[gh-actions]
+python =
+ 3.13: py313
+ 3.12: py312
+ 3.11: py311
+ 3.10: py310
diff --git a/spectre_modules/__init__.py b/spectre_modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1faff35fdb792ac4262c54b7c1d7b8262cb70f4e
--- /dev/null
+++ b/spectre_modules/__init__.py
@@ -0,0 +1,6 @@
+"""
+Modules Spectre adaptés pour Ba7ath OSINT Suite
+"""
+
+__version__ = "1.0.0"
+__author__ = "Ba7ath Team"
diff --git a/spectre_modules/domain_recon.py b/spectre_modules/domain_recon.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa4312b1cb66fba32961ba7971bd885266b9db6c
--- /dev/null
+++ b/spectre_modules/domain_recon.py
@@ -0,0 +1,252 @@
+"""
+Module de reconnaissance de domaine pour Ba7ath OSINT Suite
+Fournit : WHOIS, DNS records, découverte de sous-domaines
+100% passif et légal
+"""
+
+import whois
+import dns.resolver
+import requests
+import os
+import time
+from concurrent.futures import ThreadPoolExecutor
+from typing import Dict, List
+
+# Configuration des chemins relatifs
+CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
+REPORTS_DIR = os.path.join(CURRENT_DIR, '..', 'reports')
+SUBDOMAINS_FILE = os.path.join(CURRENT_DIR, 'wordlists', 'subdomains.txt')
+
+# Types d'enregistrements DNS à interroger
+DNS_RECORD_TYPES = ['A', 'AAAA', 'MX', 'TXT', 'NS', 'CNAME', 'SOA', 'SRV']
+
+
+def load_subdomain_wordlist(filepath: str) -> List[str]:
+ """
+ Charge une wordlist de sous-domaines depuis un fichier.
+ Retourne une liste par défaut si le fichier n'existe pas.
+ """
+ try:
+ with open(filepath, 'r', encoding='utf-8') as f:
+ wordlist = [line.strip() for line in f if line.strip()]
+ print(f"[+] Wordlist chargée : {len(wordlist)} sous-domaines")
+ return wordlist
+ except FileNotFoundError:
+ print(f"[!] Wordlist introuvable : {filepath}. Utilisation de la liste par défaut.")
+ return ['www', 'mail', 'ftp', 'admin', 'blog', 'shop', 'portal', 'api', 'dev', 'staging']
+ except Exception as e:
+ print(f"[!] Erreur de chargement de wordlist : {e}")
+ return ['www', 'mail', 'admin']
+
+
+def get_whois_info(domain: str) -> Dict:
+ """
+ Récupère les informations WHOIS d'un domaine.
+ Retourne un dictionnaire avec les données ou une erreur.
+ """
+ try:
+ w_info = whois.whois(domain)
+ # Convertir toutes les valeurs en string pour faciliter l'affichage
+ whois_data = {}
+ for key, value in w_info.items():
+ if value:
+ # Gestion des listes (ex: nameservers)
+ if isinstance(value, list):
+ whois_data[key] = ', '.join(str(v) for v in value)
+ else:
+ whois_data[key] = str(value)
+ return whois_data
+ except Exception as e:
+ return {'error': f"Impossible de récupérer WHOIS: {str(e)}"}
+
+
+def get_dns_records(domain: str) -> Dict[str, List[str]]:
+ """
+ Interroge tous les types d'enregistrements DNS pour un domaine.
+ Retourne un dictionnaire {type: [enregistrements]}.
+ """
+ dns_data = {}
+ resolver = dns.resolver.Resolver()
+ resolver.timeout = 5
+ resolver.lifetime = 5
+
+ for record_type in DNS_RECORD_TYPES:
+ try:
+ answers = resolver.resolve(domain, record_type)
+ dns_data[record_type] = [answer.to_text() for answer in answers]
+ except dns.resolver.NoAnswer:
+ dns_data[record_type] = []
+ except dns.resolver.NXDOMAIN:
+ dns_data[record_type] = ['Domaine inexistant']
+ break
+ except Exception as e:
+ dns_data[record_type] = [f"Erreur: {str(e)}"]
+
+ return dns_data
+
+
+def check_subdomain(domain: str, subdomain: str) -> str:
+ """
+ Vérifie si un sous-domaine existe via une requête HTTP HEAD.
+ Retourne le sous-domaine complet s'il existe, None sinon.
+ """
+ full_domain = f"{subdomain}.{domain}"
+
+ # Test HTTPS d'abord
+ for protocol in ['https', 'http']:
+ try:
+ response = requests.head(
+ f"{protocol}://{full_domain}",
+ timeout=3,
+ headers={'User-Agent': 'Mozilla/5.0 (Ba7ath OSINT Suite)'},
+ allow_redirects=True
+ )
+ if response.status_code < 500: # Accepter tout sauf erreurs serveur
+ return full_domain
+ except requests.RequestException:
+ continue
+
+ return None
+
+
+def discover_subdomains(domain: str, max_workers: int = 20) -> List[str]:
+ """
+ Découvre les sous-domaines actifs en testant une wordlist.
+ Utilise le multithreading pour accélérer le processus.
+ """
+ wordlist = load_subdomain_wordlist(SUBDOMAINS_FILE)
+ active_subdomains = []
+
+ print(f"[*] Test de {len(wordlist)} sous-domaines potentiels...")
+
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ futures = {executor.submit(check_subdomain, domain, sub): sub for sub in wordlist}
+
+ for future in futures:
+ result = future.result()
+ if result:
+ active_subdomains.append(result)
+ print(f"[+] Trouvé : {result}")
+
+ return sorted(active_subdomains)
+
+
+def save_report(domain: str, results: Dict) -> str:
+ """
+ Sauvegarde un rapport texte complet de la reconnaissance.
+ Retourne le nom du fichier créé.
+ """
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_filename = f"domain_recon_{domain}_{timestamp}.txt"
+ report_path = os.path.join(REPORTS_DIR, report_filename)
+
+ try:
+ os.makedirs(REPORTS_DIR, exist_ok=True)
+
+ with open(report_path, 'w', encoding='utf-8') as f:
+ f.write("=" * 60 + "\n")
+ f.write(" BA7ATH OSINT SUITE - RAPPORT DE RECONNAISSANCE\n")
+ f.write("=" * 60 + "\n\n")
+ f.write(f"Date : {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
+ f.write(f"Domaine cible : {domain}\n")
+ f.write("\n" + "=" * 60 + "\n\n")
+
+ # Sous-domaines
+ f.write("📍 SOUS-DOMAINES ACTIFS\n")
+ f.write("-" * 60 + "\n")
+ if results.get('subdomains'):
+ for sub in results['subdomains']:
+ f.write(f" ✓ {sub}\n")
+ f.write(f"\nTotal : {len(results['subdomains'])} sous-domaines trouvés\n")
+ else:
+ f.write(" Aucun sous-domaine trouvé dans la wordlist\n")
+
+ # DNS
+ f.write("\n\n🌐 ENREGISTREMENTS DNS\n")
+ f.write("-" * 60 + "\n")
+ for record_type, records in results.get('dns', {}).items():
+ if records:
+ f.write(f"\n[{record_type}]\n")
+ for record in records:
+ f.write(f" → {record}\n")
+
+ # WHOIS
+ f.write("\n\n📋 INFORMATIONS WHOIS\n")
+ f.write("-" * 60 + "\n")
+ whois_data = results.get('whois', {})
+ if 'error' not in whois_data:
+ for key, value in whois_data.items():
+ f.write(f"{key:20s} : {value}\n")
+ else:
+ f.write(f" {whois_data['error']}\n")
+
+ f.write("\n" + "=" * 60 + "\n")
+ f.write("Fin du rapport\n")
+
+ print(f"[✓] Rapport sauvegardé : {report_filename}")
+ return report_filename
+
+ except Exception as e:
+ print(f"[!] Erreur lors de la sauvegarde du rapport : {e}")
+ return None
+
+
+def run_recon(domain: str, scan_subdomains: bool = True) -> Dict:
+ """
+ Lance une reconnaissance complète d'un domaine.
+
+ Args:
+ domain: Le domaine à analyser (ex: 'example.com')
+ scan_subdomains: Si True, effectue la découverte de sous-domaines
+
+ Returns:
+ Dict contenant whois, dns, subdomains, et report_filename
+ """
+ print(f"\n[*] Début de la reconnaissance pour : {domain}")
+
+ results = {
+ 'domain': domain,
+ 'whois': {},
+ 'dns': {},
+ 'subdomains': [],
+ 'report_filename': None
+ }
+
+ # 1. WHOIS
+ print("[*] Récupération des informations WHOIS...")
+ results['whois'] = get_whois_info(domain)
+
+ # 2. DNS
+ print("[*] Interrogation des enregistrements DNS...")
+ results['dns'] = get_dns_records(domain)
+
+ # 3. Sous-domaines (optionnel)
+ if scan_subdomains:
+ print("[*] Découverte des sous-domaines...")
+ results['subdomains'] = discover_subdomains(domain)
+ else:
+ print("[*] Scan de sous-domaines désactivé")
+
+ # 4. Sauvegarde du rapport
+ print("[*] Génération du rapport...")
+ results['report_filename'] = save_report(domain, results)
+
+ print(f"[✓] Reconnaissance terminée pour {domain}\n")
+ return results
+
+
+# Test autonome du module
+if __name__ == "__main__":
+ import sys
+
+ if len(sys.argv) > 1:
+ test_domain = sys.argv[1]
+ print(f"Test du module sur : {test_domain}")
+ results = run_recon(test_domain, scan_subdomains=False)
+ print("\nRésultats :")
+ print(f" - WHOIS : {len(results['whois'])} entrées")
+ print(f" - DNS : {sum(len(v) for v in results['dns'].values())} enregistrements")
+ print(f" - Sous-domaines : {len(results['subdomains'])}")
+ else:
+ print("Usage: python domain_recon.py ")
+ print("Exemple: python domain_recon.py example.com")
diff --git a/spectre_modules/email_harvester.py b/spectre_modules/email_harvester.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7ccd9a928ef1402507f652ebc02a2e86201588f
--- /dev/null
+++ b/spectre_modules/email_harvester.py
@@ -0,0 +1,259 @@
+"""
+Module d'extraction d'emails pour Ba7ath OSINT Suite
+Extraction passive depuis pages web publiques avec validation DNS
+"""
+
+import requests
+import re
+import dns.resolver
+import time
+import pandas as pd
+import os
+from typing import List, Dict, Set
+from urllib.parse import urlparse, urljoin
+from bs4 import BeautifulSoup
+import urllib.robotparser
+
+# Configuration
+CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
+REPORTS_DIR = os.path.join(CURRENT_DIR, '..', 'reports')
+
+EMAIL_REGEX = re.compile(
+ r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
+ re.IGNORECASE
+)
+
+USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
+
+def check_robots_txt(url: str) -> bool:
+ try:
+ parsed = urlparse(url)
+ robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt"
+ rp = urllib.robotparser.RobotFileParser()
+ rp.set_url(robots_url)
+ rp.read()
+ return rp.can_fetch(USER_AGENT, url)
+ except:
+ return True
+
+def validate_email_dns(email: str) -> bool:
+ try:
+ domain = email.split('@')[1]
+ dns.resolver.resolve(domain, 'MX')
+ return True
+ except:
+ return False
+
+def extract_emails_from_text(text: str) -> Set[str]:
+ emails = set(EMAIL_REGEX.findall(text))
+ filtered_emails = set()
+ false_positives = [
+ 'example@example.com', 'test@test.com', 'admin@localhost',
+ 'user@domain.com', 'email@example.com'
+ ]
+ for email in emails:
+ email_lower = email.lower()
+ if any(fp in email_lower for fp in false_positives):
+ continue
+ if email_lower.endswith(('.png', '.jpg', '.gif', '.css', '.js')):
+ continue
+ filtered_emails.add(email)
+ return filtered_emails
+
+def scrape_url_emails(
+ url: str,
+ validate_dns: bool = True,
+ follow_links: bool = False,
+ max_depth: int = 1,
+ respect_robots_txt: bool = True,
+ depth: int = 0
+) -> Dict:
+ print(f"[*] Scraping : {url}")
+ if respect_robots_txt and not check_robots_txt(url):
+ print(f"[!] Bloqué par robots.txt : {url}")
+ return {
+ 'url': url,
+ 'emails': [],
+ 'status': 'blocked_by_robots',
+ 'error': None
+ }
+ try:
+ response = requests.get(
+ url,
+ timeout=15,
+ headers={'User-Agent': USER_AGENT},
+ allow_redirects=True
+ )
+ response.raise_for_status()
+
+ content_type = response.headers.get('Content-Type', '').lower()
+ soup = None
+ title = ''
+ emails = set()
+
+ if 'application/pdf' in content_type or url.lower().endswith('.pdf'):
+ try:
+ import PyPDF2
+ import io
+ reader = PyPDF2.PdfReader(io.BytesIO(response.content))
+ text = " ".join(page.extract_text() or "" for page in reader.pages)
+ emails = extract_emails_from_text(text)
+ title = url.split('/')[-1]
+ except Exception as e:
+ print(f"[!] Erreur extraction PDF : {e}")
+ else:
+ soup = BeautifulSoup(response.content, 'html.parser')
+ title = soup.title.string if soup.title else ''
+ # Emails trouvés sur la page
+ emails = extract_emails_from_text(response.text)
+ for link in soup.find_all('a', href=True):
+ href = link['href']
+ if href.startswith('mailto:'):
+ email = href.replace('mailto:', '').split('?')[0]
+ if EMAIL_REGEX.match(email):
+ emails.add(email)
+
+ # Agrégation emails des sous-pages (liens internes)
+ if follow_links and max_depth > 0 and depth < max_depth and soup:
+ parsed_base = urlparse(url)
+ seen_links = set()
+ for link in soup.find_all('a', href=True):
+ href = link['href']
+ full_url = urljoin(url, href)
+ parsed_link = urlparse(full_url)
+ norm_url = parsed_link.scheme + '://' + parsed_link.netloc + parsed_link.path
+ if parsed_link.netloc == parsed_base.netloc and norm_url not in seen_links:
+ seen_links.add(norm_url)
+ print(f"[*] Lien interne : {full_url}")
+ time.sleep(1)
+ sub_result = scrape_url_emails(
+ full_url,
+ validate_dns=False,
+ follow_links=False,
+ max_depth=0,
+ respect_robots_txt=respect_robots_txt,
+ depth=depth + 1
+ )
+ # Correction : on agrège bien les emails (string)
+ emails.update(email['email'] for email in sub_result['emails'])
+ # Déduplication/validation finale
+ validated_emails = []
+ for email in sorted(emails):
+ email_data = {
+ 'email': email,
+ 'source_url': url,
+ 'dns_valid': None
+ }
+ if validate_dns:
+ email_data['dns_valid'] = validate_email_dns(email)
+ validated_emails.append(email_data)
+ print(f"[+] {len(validated_emails)} emails trouvés")
+ return {
+ 'url': url,
+ 'title': title,
+ 'emails': validated_emails,
+ 'total_found': len(validated_emails),
+ 'status': 'success',
+ 'error': None
+ }
+ except requests.RequestException as e:
+ print(f"[!] Erreur HTTP : {e}")
+ return {
+ 'url': url,
+ 'emails': [],
+ 'status': 'error',
+ 'error': str(e)
+ }
+ except Exception as e:
+ print(f"[!] Erreur : {e}")
+ return {
+ 'url': url,
+ 'emails': [],
+ 'status': 'error',
+ 'error': str(e)
+ }
+
+def harvest_emails_batch(
+ urls: List[str],
+ validate_dns: bool = True,
+ follow_links: bool = False,
+ respect_robots_txt: bool = True
+) -> Dict:
+ print(f"\n[*] Début de l'extraction sur {len(urls)} URLs")
+ results = {
+ 'urls_scanned': [],
+ 'all_emails': [],
+ 'unique_emails': set(),
+ 'total_found': 0,
+ 'successful_scans': 0,
+ 'failed_scans': 0
+ }
+ for idx, url in enumerate(urls, 1):
+ print(f"\n[*] URL {idx}/{len(urls)}")
+ if not url.startswith(('http://', 'https://')):
+ url = 'https://' + url
+ scan_result = scrape_url_emails(
+ url, validate_dns, follow_links, max_depth=1, respect_robots_txt=respect_robots_txt
+ )
+ results['urls_scanned'].append(scan_result)
+ if scan_result['status'] == 'success':
+ results['successful_scans'] += 1
+ for email_data in scan_result['emails']:
+ results['all_emails'].append(email_data)
+ results['unique_emails'].add(email_data['email'])
+ else:
+ results['failed_scans'] += 1
+ time.sleep(2)
+ results['total_found'] = len(results['unique_emails'])
+ print(f"\n[✓] Extraction terminée : {results['total_found']} emails uniques")
+ return results
+
+def save_report_csv(results: Dict, base_name: str = "emails") -> str:
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_filename = f"{base_name}_{timestamp}.csv"
+ report_path = os.path.join(REPORTS_DIR, report_filename)
+ try:
+ os.makedirs(REPORTS_DIR, exist_ok=True)
+ df = pd.DataFrame(results['all_emails'])
+ df['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
+ df.to_csv(report_path, index=False, encoding='utf-8-sig')
+ print(f"[✓] Rapport CSV sauvegardé : {report_filename}")
+ return report_filename
+ except Exception as e:
+ print(f"[!] Erreur sauvegarde : {e}")
+ return None
+
+def harvest_emails(
+ urls: List[str],
+ validate_dns: bool = True,
+ follow_links: bool = False,
+ export_csv: bool = True,
+ respect_robots_txt: bool = True
+) -> Dict:
+ results = harvest_emails_batch(
+ urls, validate_dns, follow_links, respect_robots_txt
+ )
+ if export_csv and results['all_emails']:
+ results['report_filename'] = save_report_csv(results)
+ else:
+ results['report_filename'] = None
+ return results
+
+if __name__ == "__main__":
+ import sys
+ if len(sys.argv) > 1:
+ test_urls = sys.argv[1:]
+ print(f"Test du module sur {len(test_urls)} URLs")
+ results = harvest_emails(test_urls, validate_dns=True, follow_links=True)
+ print("\nRésumé :")
+ print(f" - URLs scannées : {len(results['urls_scanned'])}")
+ print(f" - Emails uniques : {results['total_found']}")
+ print(f" - Succès : {results['successful_scans']}")
+ print(f" - Échecs : {results['failed_scans']}")
+ if results['unique_emails']:
+ print("\nEmails trouvés :")
+ for email in sorted(results['unique_emails'])[:10]:
+ print(f" • {email}")
+ else:
+ print("Usage: python email_harvester.py [url2] [url3] ...")
+ print("Exemple: python email_harvester.py https://example.com")
diff --git a/spectre_modules/social_mentions.py b/spectre_modules/social_mentions.py
new file mode 100644
index 0000000000000000000000000000000000000000..63e3256fe69f7d61571b8d41b773cc358d196531
--- /dev/null
+++ b/spectre_modules/social_mentions.py
@@ -0,0 +1,63 @@
+"""
+Collecte passive des mentions publiques sur les réseaux sociaux via DuckDuckGo (sans API officielle).
+© Ba7ath OSINT Suite
+"""
+
+from ddgs import DDGS
+import time
+
+SOCIAL_SITES = {
+ "Twitter": "site:twitter.com",
+ "LinkedIn": "site:linkedin.com/in",
+ "GitHub": "site:github.com",
+ "Instagram": "site:instagram.com",
+ "Facebook": "site:facebook.com",
+ "Reddit": "site:reddit.com"
+ # Ajouter d'autres si besoin
+}
+
+def search_social_mentions(query: str, platforms: list = None, max_results: int = 15, cooldown: float = 2.0):
+ """
+ Recherche sur tous les réseaux sociaux spécifiés via DuckDuckGo.
+ Args:
+ query: Mot-clé, pseudo, nom, email...
+ platforms: Liste des plateformes
+ max_results: Max résultats par plateforme
+ cooldown: Délai entre recherches
+ Returns:
+ Dictionnaire: plateforme → liste de résultats (titres, urls, extraits)
+ """
+ if not platforms:
+ platforms = list(SOCIAL_SITES.keys())
+
+ results = {}
+ for platform in platforms:
+ site_search = SOCIAL_SITES.get(platform)
+ if not site_search:
+ continue
+ ddg_query = f'{query} {site_search}'
+ print(f"🔍 {platform}: {ddg_query}")
+ data = []
+ try:
+ hits = []
+ with DDGS() as ddgs:
+ for r in ddgs.text(ddg_query, max_results=max_results):
+ hits.append(r)
+ if hits:
+ for hit in hits:
+ data.append({
+ "title": hit.get("title"),
+ "url": hit.get("href") or hit.get("url"),
+ "snippet": hit.get("body") or hit.get("snippet")
+ })
+ except Exception as e:
+ data.append({"error": str(e)})
+ results[platform] = data
+ time.sleep(cooldown) # Antiblocage
+ return results
+
+if __name__ == "__main__":
+ # Test CLI
+ res = search_social_mentions("elon musk", ["Twitter", "LinkedIn"])
+ from pprint import pprint
+ pprint(res)
diff --git a/spectre_modules/subdomain_finder.py b/spectre_modules/subdomain_finder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8b3efec9d662155261f3561afd1d2bde0f623f3
--- /dev/null
+++ b/spectre_modules/subdomain_finder.py
@@ -0,0 +1,288 @@
+"""
+Module de découverte de sous-domaines pour Ba7ath OSINT Suite
+Sources : crt.sh, VirusTotal (optionnel)
+100% passif et légal
+"""
+
+import requests
+import time
+import pandas as pd
+import os
+from typing import List, Dict, Set
+import re
+
+# Configuration
+CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
+REPORTS_DIR = os.path.join(CURRENT_DIR, '..', 'reports')
+
+# Regex pour nettoyer les caractères invalides
+CLEAN_RE = re.compile(r'[\ud800-\udfff]')
+
+
+def clean_text(text: str) -> str:
+ """Nettoie le texte en supprimant les caractères surrogates."""
+ return CLEAN_RE.sub('', text)
+
+
+def fetch_from_crtsh(domain: str) -> List[str]:
+ """
+ Récupère les sous-domaines depuis crt.sh (Certificate Transparency logs).
+
+ Args:
+ domain: Le domaine racine (ex: 'example.com')
+
+ Returns:
+ Liste de sous-domaines uniques triés
+ """
+ print(f"[*] Interrogation de crt.sh pour {domain}...")
+
+ url = f"https://crt.sh/?q=%.{domain}&output=json"
+
+ try:
+ response = requests.get(url, timeout=30)
+ response.raise_for_status()
+ data = response.json()
+
+ subdomains: Set[str] = set()
+
+ for entry in data:
+ # Extraire common_name et name_value
+ names = [
+ entry.get("common_name", ""),
+ entry.get("name_value", "")
+ ]
+
+ for name_field in names:
+ # Gérer les multi-lignes dans name_value
+ for name in str(name_field).replace("\\n", "\n").splitlines():
+ name = name.strip().lower()
+
+ # Ignorer les wildcards et entrées vides
+ if not name or "*" in name:
+ continue
+
+ # Vérifier que c'est bien un sous-domaine du domaine cible
+ if name.endswith(f".{domain}") or name == domain:
+ subdomains.add(clean_text(name))
+
+ result = sorted(subdomains)
+ print(f"[+] crt.sh : {len(result)} sous-domaines trouvés")
+ return result
+
+ except requests.RequestException as e:
+ print(f"[!] Erreur crt.sh : {e}")
+ return []
+ except Exception as e:
+ print(f"[!] Erreur parsing crt.sh : {e}")
+ return []
+
+
+def fetch_from_virustotal(domain: str, api_key: str) -> List[str]:
+ """
+ Récupère les sous-domaines depuis VirusTotal API v3.
+
+ Args:
+ domain: Le domaine racine
+ api_key: Clé API VirusTotal
+
+ Returns:
+ Liste de sous-domaines uniques triés
+ """
+ if not api_key:
+ print("[!] Clé API VirusTotal non fournie, module ignoré")
+ return []
+
+ print(f"[*] Interrogation de VirusTotal pour {domain}...")
+
+ url = f"https://www.virustotal.com/api/v3/domains/{domain}/subdomains?limit=40"
+ headers = {"x-apikey": api_key}
+
+ subdomains: Set[str] = set()
+
+ try:
+ while url:
+ response = requests.get(url, headers=headers, timeout=15)
+ response.raise_for_status()
+ data = response.json()
+
+ # Extraire les sous-domaines de la réponse
+ for item in data.get("data", []):
+ subdomain = item.get("id", "").lower().strip()
+ if subdomain:
+ subdomains.add(clean_text(subdomain))
+
+ # Pagination
+ url = data.get("links", {}).get("next")
+
+ result = sorted(subdomains)
+ print(f"[+] VirusTotal : {len(result)} sous-domaines trouvés")
+ return result
+
+ except requests.RequestException as e:
+ print(f"[!] Erreur VirusTotal : {e}")
+ return []
+ except Exception as e:
+ print(f"[!] Erreur parsing VirusTotal : {e}")
+ return []
+
+
+def deduplicate_subdomains(sources: Dict[str, List[str]]) -> List[Dict[str, str]]:
+ """
+ Fusionne et déduplique les sous-domaines de plusieurs sources.
+
+ Args:
+ sources: Dict {source_name: [subdomains]}
+
+ Returns:
+ Liste de dicts avec subdomain, sources, first_seen
+ """
+ # Map subdomain -> liste des sources
+ subdomain_map: Dict[str, List[str]] = {}
+
+ for source_name, subdomains in sources.items():
+ for sub in subdomains:
+ if sub not in subdomain_map:
+ subdomain_map[sub] = []
+ subdomain_map[sub].append(source_name)
+
+ # Créer la liste finale
+ results = []
+ for subdomain, source_list in subdomain_map.items():
+ results.append({
+ 'subdomain': subdomain,
+ 'sources': ', '.join(sorted(set(source_list))),
+ 'source_count': len(set(source_list)),
+ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
+ })
+
+ # Trier par nombre de sources (décroissant) puis alphabétique
+ results.sort(key=lambda x: (-x['source_count'], x['subdomain']))
+
+ return results
+
+
+def save_report_csv(domain: str, results: List[Dict[str, str]]) -> str:
+ """
+ Sauvegarde un rapport CSV des sous-domaines découverts.
+
+ Args:
+ domain: Le domaine racine
+ results: Liste des résultats dédupliqués
+
+ Returns:
+ Nom du fichier créé
+ """
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_filename = f"subdomains_{domain}_{timestamp}.csv"
+ report_path = os.path.join(REPORTS_DIR, report_filename)
+
+ try:
+ os.makedirs(REPORTS_DIR, exist_ok=True)
+
+ # Créer le DataFrame
+ df = pd.DataFrame(results)
+
+ # Ajouter une colonne de domaine racine
+ df.insert(0, 'root_domain', domain)
+
+ # Sauvegarder en CSV
+ df.to_csv(report_path, index=False, encoding='utf-8-sig')
+
+ print(f"[✓] Rapport CSV sauvegardé : {report_filename}")
+ return report_filename
+
+ except Exception as e:
+ print(f"[!] Erreur lors de la sauvegarde du rapport : {e}")
+ return None
+
+
+def discover_subdomains(domain: str, virustotal_api_key: str = None) -> Dict:
+ """
+ Lance la découverte complète de sous-domaines depuis plusieurs sources.
+
+ Args:
+ domain: Le domaine racine à analyser
+ virustotal_api_key: Clé API VirusTotal (optionnel)
+
+ Returns:
+ Dict contenant les résultats et métadonnées
+ """
+ print(f"\n[*] Début de la découverte de sous-domaines pour : {domain}")
+
+ # Nettoyer le domaine
+ domain = domain.strip().lower()
+ domain = domain.replace('http://', '').replace('https://', '')
+ domain = domain.replace('www.', '')
+ domain = domain.split('/')[0]
+
+ results = {
+ 'domain': domain,
+ 'subdomains': [],
+ 'sources_used': [],
+ 'total_found': 0,
+ 'report_filename': None
+ }
+
+ sources_data = {}
+
+ # 1. crt.sh (toujours actif)
+ try:
+ crtsh_subs = fetch_from_crtsh(domain)
+ if crtsh_subs:
+ sources_data['crt.sh'] = crtsh_subs
+ results['sources_used'].append('crt.sh')
+ except Exception as e:
+ print(f"[!] Erreur crt.sh : {e}")
+
+ # 2. VirusTotal (si clé API fournie)
+ if virustotal_api_key:
+ try:
+ vt_subs = fetch_from_virustotal(domain, virustotal_api_key)
+ if vt_subs:
+ sources_data['VirusTotal'] = vt_subs
+ results['sources_used'].append('VirusTotal')
+ except Exception as e:
+ print(f"[!] Erreur VirusTotal : {e}")
+
+ # 3. Déduplication et fusion
+ if sources_data:
+ print("[*] Déduplication et fusion des résultats...")
+ deduplicated = deduplicate_subdomains(sources_data)
+ results['subdomains'] = deduplicated
+ results['total_found'] = len(deduplicated)
+
+ # 4. Sauvegarde du rapport
+ print("[*] Génération du rapport CSV...")
+ results['report_filename'] = save_report_csv(domain, deduplicated)
+ else:
+ print("[!] Aucun sous-domaine trouvé")
+
+ print(f"[✓] Découverte terminée : {results['total_found']} sous-domaines uniques\n")
+
+ return results
+
+
+# Test autonome du module
+if __name__ == "__main__":
+ import sys
+
+ if len(sys.argv) > 1:
+ test_domain = sys.argv[1]
+ vt_key = sys.argv[2] if len(sys.argv) > 2 else None
+
+ print(f"Test du module sur : {test_domain}")
+ results = discover_subdomains(test_domain, vt_key)
+
+ print("\nRésumé :")
+ print(f" - Domaine : {results['domain']}")
+ print(f" - Sources : {', '.join(results['sources_used'])}")
+ print(f" - Total : {results['total_found']} sous-domaines")
+
+ if results['subdomains']:
+ print("\nTop 10 :")
+ for sub in results['subdomains'][:10]:
+ print(f" • {sub['subdomain']} ({sub['sources']})")
+ else:
+ print("Usage: python subdomain_finder.py [cle_virustotal]")
+ print("Exemple: python subdomain_finder.py example.com")
+ print("Exemple avec VT: python subdomain_finder.py example.com YOUR_API_KEY")
diff --git a/spectre_modules/wayback_urls.py b/spectre_modules/wayback_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ff1a23fd122ed7c8fb6e2ae9cec592e4f4c8ee3
--- /dev/null
+++ b/spectre_modules/wayback_urls.py
@@ -0,0 +1,496 @@
+"""
+Module de récupération d'URLs historiques via Wayback Machine CDX API
+Avec téléchargement de contenu, extraction de texte et liens directs
+Pour Ba7ath OSINT Suite - 100% passif et légal
+"""
+
+import requests
+import time
+import pandas as pd
+import os
+from typing import List, Dict, Optional, Tuple
+import urllib.parse
+from bs4 import BeautifulSoup
+import re
+
+# Configuration
+CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
+REPORTS_DIR = os.path.join(CURRENT_DIR, '..', 'reports')
+DOWNLOADS_DIR = os.path.join(CURRENT_DIR, '..', 'downloads')
+
+# API Wayback Machine CDX
+WAYBACK_CDX_API = "https://web.archive.org/cdx/search/cdx"
+WAYBACK_BASE = "https://web.archive.org/web"
+
+
+def get_wayback_url(timestamp: str, original_url: str) -> str:
+ """Construit l'URL Wayback complète."""
+ return f"{WAYBACK_BASE}/{timestamp}/{original_url}"
+
+
+def fetch_wayback_urls(
+ domain: str,
+ filter_status: Optional[List[int]] = None,
+ filter_mimetype: Optional[List[str]] = None,
+ limit: int = 10000,
+ collapse: str = "urlkey"
+) -> List[Dict]:
+ """
+ Récupère les URLs historiques depuis Wayback Machine CDX API.
+
+ Args:
+ domain: Le domaine à analyser (ex: 'example.com')
+ filter_status: Liste de codes HTTP à inclure (ex: [200, 301])
+ filter_mimetype: Liste de MIME types à inclure (ex: ['text/html'])
+ limit: Nombre max d'URLs par requête (max 10000)
+ collapse: Méthode de déduplication ('urlkey' ou 'digest')
+
+ Returns:
+ Liste de dictionnaires contenant les URLs et métadonnées
+ """
+ print(f"[*] Interrogation de Wayback Machine pour {domain}...")
+
+ # Construction de l'URL de requête
+ params = {
+ 'url': f'*.{domain}/*',
+ 'output': 'json',
+ 'fl': 'original,timestamp,statuscode,mimetype',
+ 'collapse': collapse,
+ 'limit': limit,
+ 'showResumeKey': 'true'
+ }
+
+ # Filtres optionnels
+ if filter_status:
+ params['filter'] = f"statuscode:{','.join(map(str, filter_status))}"
+
+ all_results = []
+ resume_key = None
+ page = 0
+
+ try:
+ while True:
+ # Ajouter le resume key pour la pagination
+ if resume_key:
+ params['resumeKey'] = resume_key
+
+ print(f"[*] Récupération page {page + 1}...")
+
+ response = requests.get(WAYBACK_CDX_API, params=params, timeout=30)
+ response.raise_for_status()
+
+ data = response.json()
+
+ # Vérifier s'il y a un resume key pour la page suivante
+ next_key = None
+ if data and isinstance(data[-1], list) and len(data[-1]) == 1:
+ next_key = str(data[-1][0])
+ data = data[:-1]
+ elif data and isinstance(data[-1], dict) and 'resumeKey' in data[-1]:
+ next_key = str(data[-1].get('resumeKey'))
+ data = data[:-1]
+
+ # Traiter les résultats (ignorer la première ligne si c'est un header)
+ for idx, row in enumerate(data):
+ if idx == 0 or not row:
+ continue
+
+ try:
+ url = row[0]
+ timestamp = row[1] if len(row) > 1 else None
+ status_code = int(row[2]) if len(row) > 2 and str(row[2]).isdigit() else None
+ mime_type = row[3] if len(row) > 3 else None
+
+ # Appliquer le filtre MIME type si spécifié
+ if filter_mimetype and mime_type not in filter_mimetype:
+ continue
+
+ # Extraire le hostname
+ parsed = urllib.parse.urlsplit(url)
+ hostname = parsed.hostname or domain
+
+ # Extension du fichier
+ path = parsed.path
+ extension = ''
+ if '.' in path:
+ extension = '.' + path.split('.')[-1].lower()
+
+ all_results.append({
+ 'url': url,
+ 'hostname': hostname,
+ 'timestamp': timestamp,
+ 'status_code': status_code,
+ 'mime_type': mime_type,
+ 'extension': extension,
+ 'date_archived': format_wayback_timestamp(timestamp) if timestamp else None,
+ 'wayback_url': get_wayback_url(timestamp, url) if timestamp else None
+ })
+ except (IndexError, ValueError) as e:
+ continue
+
+ page += 1
+ print(f"[+] Page {page} : {len(data) - 1} URLs récupérées (total: {len(all_results)})")
+
+ # Arrêter si pas de page suivante
+ if not next_key:
+ break
+
+ resume_key = next_key
+
+ # Petite pause pour ne pas surcharger l'API
+ time.sleep(0.5)
+
+ print(f"[✓] Total : {len(all_results)} URLs historiques récupérées")
+ return all_results
+
+ except requests.RequestException as e:
+ print(f"[!] Erreur Wayback Machine : {e}")
+ return []
+ except Exception as e:
+ print(f"[!] Erreur parsing Wayback : {e}")
+ return []
+
+
+def format_wayback_timestamp(timestamp: str) -> str:
+ """
+ Convertit un timestamp Wayback (YYYYMMDDhhmmss) en format lisible.
+ """
+ if not timestamp or len(timestamp) < 14:
+ return timestamp
+
+ try:
+ year = timestamp[0:4]
+ month = timestamp[4:6]
+ day = timestamp[6:8]
+ hour = timestamp[8:10]
+ minute = timestamp[10:12]
+ second = timestamp[12:14]
+
+ return f"{year}-{month}-{day} {hour}:{minute}:{second}"
+ except:
+ return timestamp
+
+
+def download_archived_file(url: str, timestamp: str, save_dir: str = None) -> Tuple[bool, str]:
+ """
+ Télécharge un fichier depuis Wayback Machine.
+
+ Args:
+ url: L'URL originale du fichier
+ timestamp: Le timestamp Wayback
+ save_dir: Répertoire de sauvegarde (défaut: DOWNLOADS_DIR)
+
+ Returns:
+ (succès, chemin_fichier)
+ """
+ if not save_dir:
+ save_dir = DOWNLOADS_DIR
+
+ os.makedirs(save_dir, exist_ok=True)
+
+ wayback_url = get_wayback_url(timestamp, url)
+
+ try:
+ # Extraire le nom du fichier
+ parsed = urllib.parse.urlparse(url)
+ filename = os.path.basename(parsed.path) or 'index.html'
+
+ # Nettoyer le nom de fichier
+ filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
+
+ # Ajouter timestamp pour éviter les collisions
+ name, ext = os.path.splitext(filename)
+ filename = f"{name}_{timestamp}{ext}"
+
+ save_path = os.path.join(save_dir, filename)
+
+ print(f"[*] Téléchargement : {filename}...")
+ response = requests.get(wayback_url, timeout=30, stream=True)
+ response.raise_for_status()
+
+ with open(save_path, 'wb') as f:
+ for chunk in response.iter_content(chunk_size=8192):
+ f.write(chunk)
+
+ print(f"[✓] Sauvegardé : {save_path}")
+ return True, save_path
+
+ except Exception as e:
+ print(f"[!] Erreur téléchargement : {e}")
+ return False, ""
+
+
+def extract_text_from_archived_page(url: str, timestamp: str) -> str:
+ """
+ Extrait le texte d'une page HTML archivée.
+
+ Args:
+ url: L'URL originale de la page
+ timestamp: Le timestamp Wayback
+
+ Returns:
+ Texte extrait de la page
+ """
+ wayback_url = get_wayback_url(timestamp, url)
+
+ try:
+ response = requests.get(wayback_url, timeout=30)
+ response.raise_for_status()
+
+ soup = BeautifulSoup(response.content, 'html.parser')
+
+ # Supprimer les éléments non pertinents
+ for element in soup(['script', 'style', 'nav', 'footer', 'header']):
+ element.decompose()
+
+ # Extraire le texte
+ text = soup.get_text(separator='\n', strip=True)
+
+ # Nettoyer les lignes vides
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+
+ return '\n'.join(lines)
+
+ except Exception as e:
+ print(f"[!] Erreur extraction texte : {e}")
+ return ""
+
+
+def analyze_urls(urls: List[Dict]) -> Dict:
+ """
+ Analyse les URLs récupérées et génère des statistiques.
+ """
+ if not urls:
+ return {}
+
+ stats = {
+ 'total_urls': len(urls),
+ 'unique_hostnames': len(set(u['hostname'] for u in urls)),
+ 'status_codes': {},
+ 'mime_types': {},
+ 'file_extensions': {},
+ 'interesting_files': [],
+ 'html_pages': []
+ }
+
+ # Extensions intéressantes pour OSINT
+ interesting_extensions = [
+ '.zip', '.tar', '.gz', '.sql', '.db', '.bak', '.old',
+ '.env', '.config', '.xml', '.json', '.csv', '.xls', '.xlsx',
+ '.pdf', '.doc', '.docx', '.txt', '.log'
+ ]
+
+ for url_data in urls:
+ # Statistiques par code HTTP
+ status = url_data['status_code']
+ if status:
+ stats['status_codes'][status] = stats['status_codes'].get(status, 0) + 1
+
+ # Statistiques par MIME type
+ mime = url_data['mime_type']
+ if mime:
+ stats['mime_types'][mime] = stats['mime_types'].get(mime, 0) + 1
+
+ # Extension
+ ext = url_data['extension']
+ if ext:
+ stats['file_extensions'][ext] = stats['file_extensions'].get(ext, 0) + 1
+
+ # Fichiers intéressants
+ if ext in interesting_extensions:
+ stats['interesting_files'].append({
+ 'url': url_data['url'],
+ 'wayback_url': url_data['wayback_url'],
+ 'extension': ext,
+ 'timestamp': url_data['timestamp'],
+ 'date_archived': url_data['date_archived']
+ })
+
+ # Pages HTML pour extraction de texte
+ if mime and 'html' in mime.lower():
+ stats['html_pages'].append({
+ 'url': url_data['url'],
+ 'wayback_url': url_data['wayback_url'],
+ 'timestamp': url_data['timestamp'],
+ 'date_archived': url_data['date_archived']
+ })
+
+ return stats
+
+
+def download_interesting_files(urls: List[Dict], max_files: int = 50) -> List[str]:
+ """
+ Télécharge automatiquement les fichiers intéressants.
+
+ Args:
+ urls: Liste des URLs avec métadonnées
+ max_files: Nombre maximum de fichiers à télécharger
+
+ Returns:
+ Liste des chemins de fichiers téléchargés
+ """
+ interesting_extensions = [
+ '.zip', '.tar', '.gz', '.sql', '.db', '.bak',
+ '.env', '.config', '.xml', '.json', '.csv',
+ '.pdf', '.doc', '.docx', '.xls', '.xlsx'
+ ]
+
+ downloaded = []
+ count = 0
+
+ print(f"\n[*] Téléchargement automatique des fichiers intéressants (max {max_files})...")
+
+ for url_data in urls:
+ if count >= max_files:
+ break
+
+ ext = url_data['extension']
+ if ext in interesting_extensions:
+ success, path = download_archived_file(
+ url_data['url'],
+ url_data['timestamp']
+ )
+
+ if success:
+ downloaded.append(path)
+ count += 1
+
+ print(f"[✓] {len(downloaded)} fichiers téléchargés")
+ return downloaded
+
+
+def save_report_csv(domain: str, urls: List[Dict], stats: Dict) -> str:
+ """
+ Sauvegarde un rapport CSV des URLs Wayback.
+ """
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ report_filename = f"wayback_urls_{domain}_{timestamp}.csv"
+ report_path = os.path.join(REPORTS_DIR, report_filename)
+
+ try:
+ os.makedirs(REPORTS_DIR, exist_ok=True)
+
+ # Créer le DataFrame principal
+ df = pd.DataFrame(urls)
+
+ # Réorganiser les colonnes
+ columns_order = ['url', 'hostname', 'date_archived', 'status_code', 'mime_type',
+ 'extension', 'wayback_url', 'timestamp']
+ df = df[columns_order]
+
+ # Sauvegarder en CSV
+ df.to_csv(report_path, index=False, encoding='utf-8-sig')
+
+ print(f"[✓] Rapport CSV sauvegardé : {report_filename}")
+ return report_filename
+
+ except Exception as e:
+ print(f"[!] Erreur lors de la sauvegarde du rapport : {e}")
+ return None
+
+
+def discover_wayback_urls(
+ domain: str,
+ filter_status: Optional[List[int]] = None,
+ filter_mimetype: Optional[List[str]] = None,
+ limit: int = 10000,
+ auto_download: bool = False,
+ max_downloads: int = 50
+) -> Dict:
+ """
+ Lance la découverte complète des URLs Wayback pour un domaine.
+
+ Args:
+ domain: Le domaine à analyser
+ filter_status: Codes HTTP à filtrer (optionnel)
+ filter_mimetype: MIME types à filtrer (optionnel)
+ limit: Nombre max d'URLs par page
+ auto_download: Télécharger automatiquement les fichiers intéressants
+ max_downloads: Nombre max de fichiers à télécharger
+
+ Returns:
+ Dict contenant les URLs, statistiques et métadonnées
+ """
+ print(f"\n[*] Début de la récupération Wayback pour : {domain}")
+
+ # Nettoyer le domaine
+ domain = domain.strip().lower()
+ domain = domain.replace('http://', '').replace('https://', '')
+ domain = domain.replace('www.', '')
+ domain = domain.split('/')[0]
+
+ results = {
+ 'domain': domain,
+ 'urls': [],
+ 'stats': {},
+ 'downloaded_files': [],
+ 'filters_applied': {
+ 'status_codes': filter_status,
+ 'mime_types': filter_mimetype
+ },
+ 'report_filename': None
+ }
+
+ # 1. Récupération des URLs
+ urls = fetch_wayback_urls(
+ domain,
+ filter_status=filter_status,
+ filter_mimetype=filter_mimetype,
+ limit=limit
+ )
+
+ if urls:
+ results['urls'] = urls
+
+ # 2. Analyse
+ print("[*] Analyse des URLs...")
+ stats = analyze_urls(urls)
+ results['stats'] = stats
+
+ # 3. Téléchargement automatique (si activé)
+ if auto_download and stats.get('interesting_files'):
+ downloaded = download_interesting_files(urls, max_downloads)
+ results['downloaded_files'] = downloaded
+
+ # 4. Sauvegarde
+ print("[*] Génération du rapport CSV...")
+ results['report_filename'] = save_report_csv(domain, urls, stats)
+ else:
+ print("[!] Aucune URL trouvée")
+
+ print(f"[✓] Découverte terminée : {len(urls)} URLs\n")
+
+ return results
+
+
+# Test autonome du module
+if __name__ == "__main__":
+ import sys
+
+ if len(sys.argv) > 1:
+ test_domain = sys.argv[1]
+ auto_dl = '--download' in sys.argv
+
+ print(f"Test du module sur : {test_domain}")
+ results = discover_wayback_urls(
+ test_domain,
+ filter_status=[200],
+ auto_download=auto_dl,
+ max_downloads=10
+ )
+
+ print("\nRésumé :")
+ print(f" - Domaine : {results['domain']}")
+ print(f" - URLs trouvées : {len(results['urls'])}")
+
+ if results['stats']:
+ print(f" - Hostnames uniques : {results['stats']['unique_hostnames']}")
+ print(f" - Fichiers intéressants : {len(results['stats']['interesting_files'])}")
+ print(f" - Pages HTML : {len(results['stats']['html_pages'])}")
+
+ if results['downloaded_files']:
+ print(f" - Fichiers téléchargés : {len(results['downloaded_files'])}")
+ else:
+ print("Usage: python wayback_urls.py [--download]")
+ print("Exemple: python wayback_urls.py example.com")
+ print("Exemple avec téléchargement: python wayback_urls.py example.com --download")
diff --git a/spectre_modules/wordlists/subdomains.txt b/spectre_modules/wordlists/subdomains.txt
new file mode 100644
index 0000000000000000000000000000000000000000..70bb403fdf6e938cd3e85bda301cff13bc8e8fbc
--- /dev/null
+++ b/spectre_modules/wordlists/subdomains.txt
@@ -0,0 +1,165 @@
+www
+mail
+ftp
+admin
+blog
+shop
+portal
+api
+dev
+staging
+test
+demo
+cdn
+m
+mobile
+app
+store
+webmail
+secure
+vpn
+remote
+intranet
+extranet
+ns1
+ns2
+ns3
+smtp
+pop
+imap
+mysql
+db
+database
+backup
+old
+new
+beta
+alpha
+prod
+production
+support
+help
+forum
+community
+chat
+video
+stream
+media
+images
+img
+static
+assets
+files
+download
+upload
+cpanel
+whm
+webdisk
+autodiscover
+autoconfig
+sip
+voip
+conference
+meet
+calendar
+crm
+erp
+hr
+finance
+sales
+marketing
+docs
+wiki
+kb
+news
+events
+careers
+jobs
+talent
+recruiting
+partners
+affiliates
+reseller
+wholesale
+b2b
+b2c
+members
+account
+login
+register
+signup
+checkout
+cart
+payment
+billing
+invoice
+dashboard
+panel
+control
+status
+monitoring
+analytics
+stats
+reports
+logs
+search
+directory
+catalog
+gallery
+portfolio
+projects
+clients
+testimonials
+reviews
+feedback
+survey
+contact
+about
+press
+legal
+privacy
+terms
+sitemap
+rss
+feeds
+xml
+json
+rest
+soap
+graphql
+ws
+websocket
+oauth
+auth
+sso
+ldap
+radius
+kerberos
+git
+svn
+hg
+ci
+cd
+jenkins
+gitlab
+github
+bitbucket
+jira
+confluence
+slack
+teams
+zoom
+skype
+webex
+gotomeeting
+hangouts
+webrtc
+turn
+stun
+sbc
+pbx
+asterisk
+freepbx
+elastix
+opensips
+kamailio
diff --git a/spiderfoot/.dockerignore b/spiderfoot/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..1c27355b1cfa684760dd7489f29178f7b06ade68
--- /dev/null
+++ b/spiderfoot/.dockerignore
@@ -0,0 +1,18 @@
+.git/
+
+build
+dist
+*.egg-info
+*.egg/
+*.pyc
+*.swp
+
+venv/
+cache/
+log/
+spiderfoot.db*
+spiderfoot.test.db
+
+__pycache__
+htmlcov/
+docs/
diff --git a/spiderfoot/.github/ISSUE_TEMPLATE.md b/spiderfoot/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 0000000000000000000000000000000000000000..6382989684f1e110c9ff7c30dde880bdecf23ecd
--- /dev/null
+++ b/spiderfoot/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,12 @@
+Please provide a description of the issue and any relevant error messages.
+
+If you can provide an application stack trace that is even better.
+
+What version of Python are you using?
+
+What version of SpiderFoot are you using (stable release or Git `master` branch)?
+
+You may also wish to check if your issue has been posted previously:
+
+* https://github.com/smicallef/spiderfoot/issues
+
diff --git a/spiderfoot/.github/workflows/codeql-analysis.yml b/spiderfoot/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8e5b95a9dd483c7293b23f071a97ab873c20ff0e
--- /dev/null
+++ b/spiderfoot/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,28 @@
+name: "CodeQL"
+
+on:
+ push:
+ branches:
+ - master
+ schedule:
+ - cron: "26 16 * * 0"
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: true
+ matrix:
+ language: ["python"]
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v2
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v1
+ with:
+ languages: ${{ matrix.language }}
+ - name: Autobuild
+ uses: github/codeql-action/autobuild@v1
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v1
diff --git a/spiderfoot/.github/workflows/tests.yaml b/spiderfoot/.github/workflows/tests.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..43bf0b56d61a72274ae9e0410844f8b0b45cb674
--- /dev/null
+++ b/spiderfoot/.github/workflows/tests.yaml
@@ -0,0 +1,39 @@
+name: Tests
+
+on:
+ push:
+ branches: master
+ pull_request:
+ branches: master
+
+jobs:
+ build:
+
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ python-version: ["3.7", "3.8", "3.9", "3.10"]
+ os: [ubuntu-latest, macos-latest]
+
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install flake8 pytest
+ pip install -r test/requirements.txt
+ - name: Lint with flake8
+ run: |
+ # stop the build if there are Python Flake8 violations
+ flake8 . --count --show-source --statistics
+ - name: Test with pytest
+ run: |
+ python -m pytest -n auto --dist loadfile --ignore=test/integration/modules/ --durations=5 --cov-report term --cov=. .
+ - uses: codecov/codecov-action@v1
+ with:
+ fail_ci_if_error: false
+ verbose: true
diff --git a/spiderfoot/.gitignore b/spiderfoot/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..44e80df4c99e1b28f54604ce159fc101d2d1efc7
--- /dev/null
+++ b/spiderfoot/.gitignore
@@ -0,0 +1,175 @@
+# SpiderFoot specific #
+#######################
+/cache/
+/log/
+/spiderfoot.db*
+passwd
+spiderfoot.crt
+spiderfoot.key
+
+spiderfoot/static/node_modules/*
+
+spiderfoot/static/node_modules/alertifyjs/*
+spiderfoot/static/node_modules/alertifyjs/build/*
+spiderfoot/static/node_modules/alertifyjs/build/css/*
+
+!spiderfoot/static/node_modules/alertifyjs/
+!spiderfoot/static/node_modules/alertifyjs/build/
+!spiderfoot/static/node_modules/alertifyjs/build/alertify.min.js
+!spiderfoot/static/node_modules/alertifyjs/build/css/
+!spiderfoot/static/node_modules/alertifyjs/build/css/alertify.min.css
+
+spiderfoot/static/node_modules/bootstrap/*
+spiderfoot/static/node_modules/bootstrap/dist/*
+spiderfoot/static/node_modules/bootstrap/dist/js/*
+spiderfoot/static/node_modules/bootstrap/dist/css/*
+spiderfoot/static/node_modules/bootstrap/dist/fonts/*
+
+!spiderfoot/static/node_modules/bootstrap/
+!spiderfoot/static/node_modules/bootstrap/dist/
+!spiderfoot/static/node_modules/bootstrap/dist/js/
+!spiderfoot/static/node_modules/bootstrap/dist/js/bootstrap.min.js
+!spiderfoot/static/node_modules/bootstrap/dist/css/
+!spiderfoot/static/node_modules/bootstrap/dist/css/bootstrap.min.css
+!spiderfoot/static/node_modules/bootstrap/dist/fonts/
+!spiderfoot/static/node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff
+!spiderfoot/static/node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2
+
+spiderfoot/static/node_modules/jquery/*
+spiderfoot/static/node_modules/jquery/dist/*
+
+!spiderfoot/static/node_modules/jquery/
+!spiderfoot/static/node_modules/jquery/dist/
+!spiderfoot/static/node_modules/jquery/dist/jquery.min.js
+
+spiderfoot/static/node_modules/sigma/*
+spiderfoot/static/node_modules/sigma/build/*
+spiderfoot/static/node_modules/sigma/build/plugins/*
+
+!spiderfoot/static/node_modules/sigma/
+!spiderfoot/static/node_modules/sigma/build/
+!spiderfoot/static/node_modules/sigma/build/sigma.min.js
+!spiderfoot/static/node_modules/sigma/build/plugins/
+!spiderfoot/static/node_modules/sigma/build/plugins/sigma.parsers.json.min.js
+!spiderfoot/static/node_modules/sigma/build/plugins/sigma.plugins.dragNodes.min.js
+!spiderfoot/static/node_modules/sigma/build/plugins/sigma.layout.forceAtlas2.min.js
+!spiderfoot/static/node_modules/sigma/build/plugins/sigma.renderers.snapshot.min.js
+
+spiderfoot/static/node_modules/tablesorter/*
+spiderfoot/static/node_modules/tablesorter/dist/*
+spiderfoot/static/node_modules/tablesorter/dist/js/*
+spiderfoot/static/node_modules/tablesorter/dist/css/*
+spiderfoot/static/node_modules/tablesorter/dist/js/extras/*
+
+!spiderfoot/static/node_modules/tablesorter/
+!spiderfoot/static/node_modules/tablesorter/dist/
+!spiderfoot/static/node_modules/tablesorter/dist/css/
+!spiderfoot/static/node_modules/tablesorter/dist/css/jquery.tablesorter.pager.min.css
+!spiderfoot/static/node_modules/tablesorter/dist/css/theme.default.min.css
+!spiderfoot/static/node_modules/tablesorter/dist/js/
+!spiderfoot/static/node_modules/tablesorter/dist/js/jquery.tablesorter.min.js
+!spiderfoot/static/node_modules/tablesorter/dist/js/jquery.tablesorter.widgets.min.js
+!spiderfoot/static/node_modules/tablesorter/dist/js/extras/
+!spiderfoot/static/node_modules/tablesorter/dist/js/extras/jquery.tablesorter.pager.min.js
+
+spiderfoot/static/node_modules/d3/*
+
+!spiderfoot/static/node_modules/d3/
+!spiderfoot/static/node_modules/d3/d3.min.js
+
+# Compiled source #
+###################
+__pycache__/
+*.com
+*.class
+*.dll
+*.exe
+*.o
+*.so
+*.py[cod]
+*$py.class
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# Packages #
+############
+# it's better to unpack these files and commit the raw source
+# git has its own built in compression methods
+*.7z
+*.dmg
+*.gz
+*.iso
+*.jar
+*.rar
+*.tar
+*.zip
+
+# Logs and databases #
+######################
+*.log
+*.sqlite
+*.db
+
+# OS generated files #
+######################
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+.*~
+Icon?
+ehthumbs.db
+Thumbs.db
+
+# Virtual environments #
+########################
+venv/
+venv3/
+
+# IDE #
+#######
+.idea
+.vscode
+
+# Test & Coverage Reports #
+###########################
+.coverage
+coverage/
+test/acceptance/results/
+htmlcov/
+report/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Documentation #
+#################
+docs/_build/
diff --git a/spiderfoot/.pylintrc b/spiderfoot/.pylintrc
new file mode 100644
index 0000000000000000000000000000000000000000..c1658cd1b1f336b8959354adb6ac77a92761970d
--- /dev/null
+++ b/spiderfoot/.pylintrc
@@ -0,0 +1,449 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code
+extension-pkg-whitelist=
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=CVS
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint.
+jobs=4
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Specify a configuration file.
+#rcfile=
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+disable=invalid-name,
+ no-self-use,
+ too-few-public-methods,
+ too-many-ancestors,
+ too-many-arguments,
+ too-many-boolean-expressions,
+ too-many-branches,
+ too-many-instance-attributes,
+ too-many-locals,
+ too-many-nested-blocks,
+ too-many-public-methods,
+ too-many-return-statements,
+ too-many-statements,
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio).You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+#output-format=text
+output-format=parseable
+
+# Tells whether to display a full report or only the messages
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=optparse.Values,sys.exit
+
+
+[BASIC]
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style
+argument-rgx=^[a-z][a-z0-9_]*$
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style
+attr-rgx=^_{0,2}[a-z][a-z0-9_]*$
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style
+class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
+
+# Regular expression matching correct class names. Overrides class-naming-style
+class-rgx=^_?[A-Z][a-zA-Z0-9]*$
+
+# Naming style matching correct constant names
+const-naming-style=UPPER_CASE
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style
+function-rgx=^(?:(?PsetUp|tearDown|setUpModule|tearDownModule)|(?P_?[A-Z][a-zA-Z0-9]*)|(?P_?[a-z][a-z0-9_]*))$
+
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=main,
+ sf,
+ _
+
+# Include a hint for the correct naming format with invalid-name
+include-naming-hint=no
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style
+inlinevar-rgx=^[a-z][a-z0-9_]*$
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style
+method-rgx=(?x)^(?:(?P_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P_{0,2}[a-z][a-z0-9_]*))$
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style
+module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style
+variable-rgx=^[a-z][a-z0-9_]*$
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: en_US (myspell), en
+# (aspell), en_AU (aspell), en_CA (aspell), en_GB (aspell).
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[LOGGING]
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format
+logging-modules=logging
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=(?x)(
+ ^\s*(\#\ )??$|
+ ^\s*(from\s+\S+\s+)?import\s+.+$)
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Maximum number of characters on a single line.
+max-line-length=120
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# List of optional constructs for which whitespace checking is disabled. `dict-
+# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
+# `trailing-comma` allows a space between comma and closing bracket: (a, ).
+# `empty-line` allows space-only lines.
+no-space-check=trailing-comma
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+ XXX,
+ TODO
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+ _cb
+
+# A regular expression matching the name of dummy variables (i.e. expectedly
+# not used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,io,builtins
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in a if statement
+max-bool-expr=5
+
+# Maximum number of branch for function / method body
+max-branches=12
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls,
+ class_
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
+
+
+[IMPORTS]
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,
+ TERMIOS,
+ Bastion,
+ rexec,
+ sets
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "Exception"
+overgeneral-exceptions=Exception,
+ BaseException,
diff --git a/spiderfoot/Dockerfile b/spiderfoot/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..9a5344858f1e9fc1019d19120d9b59493f1c444e
--- /dev/null
+++ b/spiderfoot/Dockerfile
@@ -0,0 +1,85 @@
+#
+# Spiderfoot Dockerfile
+#
+# http://www.spiderfoot.net
+#
+# Written by: Michael Pellon
+# Updated by: Chandrapal
+# Updated by: Steve Micallef
+# Updated by: Steve Bate
+# -> Inspired by https://github.com/combro2k/dockerfiles/tree/master/alpine-spiderfoot
+#
+# Usage:
+#
+# sudo docker build -t spiderfoot .
+# sudo docker run -p 5001:5001 --security-opt no-new-privileges spiderfoot
+#
+# Using Docker volume for spiderfoot data
+#
+# sudo docker run -p 5001:5001 -v /mydir/spiderfoot:/var/lib/spiderfoot spiderfoot
+#
+# Using SpiderFoot remote command line with web server
+#
+# docker run --rm -it spiderfoot sfcli.py -s http://my.spiderfoot.host:5001/
+#
+# Running spiderfoot commands without web server (can optionally specify volume)
+#
+# sudo docker run --rm spiderfoot sf.py -h
+#
+# Running a shell in the container for maintenance
+# sudo docker run -it --entrypoint /bin/sh spiderfoot
+#
+# Running spiderfoot unit tests in container
+#
+# sudo docker build -t spiderfoot-test --build-arg REQUIREMENTS=test/requirements.txt .
+# sudo docker run --rm spiderfoot-test -m pytest --flake8 .
+
+FROM alpine:3.12.4 AS build
+ARG REQUIREMENTS=requirements.txt
+RUN apk add --no-cache gcc git curl python3 python3-dev py3-pip swig tinyxml-dev \
+ python3-dev musl-dev openssl-dev libffi-dev libxslt-dev libxml2-dev jpeg-dev \
+ openjpeg-dev zlib-dev cargo rust
+RUN python3 -m venv /opt/venv
+ENV PATH="/opt/venv/bin":$PATH
+COPY $REQUIREMENTS requirements.txt ./
+RUN ls
+RUN echo "$REQUIREMENTS"
+RUN pip3 install -U pip
+RUN pip3 install -r "$REQUIREMENTS"
+
+
+
+FROM alpine:3.13.0
+WORKDIR /home/spiderfoot
+
+# Place database and logs outside installation directory
+ENV SPIDERFOOT_DATA /var/lib/spiderfoot
+ENV SPIDERFOOT_LOGS /var/lib/spiderfoot/log
+ENV SPIDERFOOT_CACHE /var/lib/spiderfoot/cache
+
+# Run everything as one command so that only one layer is created
+RUN apk --update --no-cache add python3 musl openssl libxslt tinyxml libxml2 jpeg zlib openjpeg \
+ && addgroup spiderfoot \
+ && adduser -G spiderfoot -h /home/spiderfoot -s /sbin/nologin \
+ -g "SpiderFoot User" -D spiderfoot \
+ && rm -rf /var/cache/apk/* \
+ && rm -rf /lib/apk/db \
+ && rm -rf /root/.cache \
+ && mkdir -p $SPIDERFOOT_DATA || true \
+ && mkdir -p $SPIDERFOOT_LOGS || true \
+ && mkdir -p $SPIDERFOOT_CACHE || true \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_DATA \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_LOGS \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_CACHE
+
+COPY . .
+COPY --from=build /opt/venv /opt/venv
+ENV PATH="/opt/venv/bin:$PATH"
+
+USER spiderfoot
+
+EXPOSE 5001
+
+# Run the application.
+ENTRYPOINT ["/opt/venv/bin/python"]
+CMD ["sf.py", "-l", "0.0.0.0:5001"]
diff --git a/spiderfoot/Dockerfile.full b/spiderfoot/Dockerfile.full
new file mode 100644
index 0000000000000000000000000000000000000000..a26d44ca976484d7f26ac23c5dcae678e641dd51
--- /dev/null
+++ b/spiderfoot/Dockerfile.full
@@ -0,0 +1,134 @@
+#
+# Spiderfoot Dockerfile (Full - includes all CLI tools, etc.)
+#
+# http://www.spiderfoot.net
+#
+# Written by: TheTechromancer
+#
+
+FROM python:3
+
+# Install tools/dependencies from apt
+RUN apt-get -y update && apt-get -y install nbtscan onesixtyone nmap
+
+# Compile other tools from source
+RUN mkdir /tools || true
+WORKDIR /tools
+
+# Install Golang tools
+RUN apt-get -y update && apt-get -y install golang
+ENV GOPATH="/go"
+ENV PATH="$GOPATH/bin:$PATH"
+RUN mkdir -p "$GOPATH/src" "$GOPATH/bin"
+
+# Install Ruby tools for WhatWeb
+RUN apt-get -y update && apt-get -y install ruby ruby-dev bundler
+# Install WhatWeb
+RUN git clone https://github.com/urbanadventurer/WhatWeb \
+ && gem install rchardet mongo json && cd /tools/WhatWeb \
+ && bundle install && cd /tools
+
+RUN groupadd spiderfoot \
+ && useradd -m -g spiderfoot -d /home/spiderfoot -s /sbin/nologin \
+ -c "SpiderFoot User" spiderfoot
+
+# Install RetireJS
+RUN apt remove -y cmdtest \
+ && apt remove -y yarn \
+ && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
+ && echo 'deb https://dl.yarnpkg.com/debian/ stable main' |tee /etc/apt/sources.list.d/yarn.list \
+ && apt-get update \
+ && apt-get install yarn -y \
+ && yarn install \
+ && curl -fsSL https://deb.nodesource.com/setup_17.x | bash - \
+ && apt-get install -y nodejs \
+ && npm install -g retire
+
+# Install Google Chrome the New Way (Not via apt-key)
+RUN wget -qO - https://dl.google.com/linux/linux_signing_key.pub | gpg --dearmor -o /usr/share/keyrings/googlechrome-linux-keyring.gpg \
+ && echo "deb [arch=amd64 signed-by=/usr/share/keyrings/googlechrome-linux-keyring.gpg] http://dl.google.com/linux/chrome/deb/ stable main" | tee /etc/apt/sources.list.d/google-chrome.list \
+ && apt -y update && apt install --allow-unauthenticated -y google-chrome-stable
+
+# Install Wappalyzer
+RUN git clone https://github.com/AliasIO/wappalyzer.git \
+ && cd wappalyzer \
+ && yarn install && yarn run link
+
+# Install Nuclei
+RUN wget https://github.com/projectdiscovery/nuclei/releases/download/v2.6.5/nuclei_2.6.5_linux_amd64.zip \
+ && unzip nuclei_2.6.5_linux_amd64.zip \
+ && git clone https://github.com/projectdiscovery/nuclei-templates.git
+
+# Install testssl.sh
+RUN apt-get install -y bsdmainutils dnsutils coreutils
+RUN git clone https://github.com/drwetter/testssl.sh.git
+
+# Install Snallygaster and TruffleHog
+RUN pip3 install snallygaster trufflehog
+
+# Place database and logs outside installation directory
+ENV SPIDERFOOT_DATA /var/lib/spiderfoot
+ENV SPIDERFOOT_LOGS /var/lib/spiderfoot/log
+ENV SPIDERFOOT_CACHE /var/lib/spiderfoot/cache
+
+RUN mkdir -p $SPIDERFOOT_DATA || true \
+ && mkdir -p $SPIDERFOOT_LOGS || true \
+ && mkdir -p $SPIDERFOOT_CACHE || true \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_DATA \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_LOGS \
+ && chown spiderfoot:spiderfoot $SPIDERFOOT_CACHE
+
+WORKDIR /home/spiderfoot
+COPY . .
+
+ENV VIRTUAL_ENV=/opt/venv
+RUN mkdir -p "$VIRTUAL_ENV" || true
+ENV PATH="$VIRTUAL_ENV/bin:$PATH"
+RUN python -m venv "$VIRTUAL_ENV"
+
+ARG REQUIREMENTS=requirements.txt
+COPY "$REQUIREMENTS" requirements.txt
+
+RUN chown -R spiderfoot:spiderfoot /tools
+RUN chown -R spiderfoot:spiderfoot "$VIRTUAL_ENV"
+RUN chown -R spiderfoot:spiderfoot "/home/spiderfoot"
+
+USER spiderfoot
+
+RUN pip install -U pip
+RUN pip install -r "$REQUIREMENTS"
+
+# Install Python tools
+RUN pip install dnstwist
+# CMSeeK
+WORKDIR /tools
+RUN git clone https://github.com/Tuhinshubhra/CMSeeK && cd CMSeeK \
+ && pip install -r requirements.txt && mkdir Results
+
+# Install wafw00f
+RUN git clone https://github.com/EnableSecurity/wafw00f \
+ && cd wafw00f \
+ && python3 setup.py install
+WORKDIR /home/spiderfoot
+
+EXPOSE 5001
+
+# Run the application
+CMD python -c 'from spiderfoot import SpiderFootDb; \
+db = SpiderFootDb({"__database": "/var/lib/spiderfoot/spiderfoot.db"}); \
+db.configSet({ \
+ "sfp_tool_dnstwist:dnstwistpath": "/opt/venv/bin/dnstwist", \
+ "sfp_tool_cmseek:cmseekpath": "/tools/CMSeeK/cmseek.py", \
+ "sfp_tool_whatweb:whatweb_path": "/tools/WhatWeb/whatweb", \
+ "sfp_tool_wafw00f:wafw00f_path": "/opt/venv/bin/wafw00f", \
+ "sfp_tool_onesixtyone:onesixtyone_path": "/usr/bin/onesixtyone", \
+ "sfp_tool_retirejs:retirejs_path": "/usr/bin/retire", \
+ "sfp_tool_testsslsh:testsslsh_path": "/tools/testssl.sh/testssl.sh", \
+ "sfp_tool_snallygaster:snallygaster_path": "/usr/local/bin/snallygaster", \
+ "sfp_tool_trufflehog:trufflehog_path": "/usr/local/bin/trufflehog", \
+ "sfp_tool_nuclei:nuclei_path": "/tools/nuclei", \
+ "sfp_tool_nuclei:template_path": "/tools/nuclei-templates", \
+ "sfp_tool_wappalyzer:wappalyzer_path": "/tools/wappalyzer/src/drivers/npm/cli.js", \
+ "sfp_tool_nbtscan:nbtscan_path": "/usr/bin/nbtscan", \
+ "sfp_tool_nmap:nmappath": "DISABLED_BECAUSE_NMAP_REQUIRES_ROOT_TO_WORK" \
+})' || true && ./sf.py -l 0.0.0.0:5001
diff --git a/spiderfoot/LICENSE b/spiderfoot/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..cb8ba74e8636fc9e7309ce6ff13f102c0975327f
--- /dev/null
+++ b/spiderfoot/LICENSE
@@ -0,0 +1,7 @@
+Copyright 2022 Steve Micallef
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/spiderfoot/README.md b/spiderfoot/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..a4e6ad43414067b80e804513f66d8e4f8b84822e
--- /dev/null
+++ b/spiderfoot/README.md
@@ -0,0 +1,366 @@
+
+
+
+[](https://raw.githubusercontent.com/smicallef/spiderfoot/master/LICENSE)
+[](https://www.python.org)
+[](https://github.com/smicallef/spiderfoot/releases/tag/v4.0)
+[](https://github.com/smicallef/spiderfoot/actions?query=workflow%3A"Tests")
+[](https://github.com/smicallef/spiderfoot/commits/master)
+[](https://codecov.io/github/smicallef/spiderfoot)
+[](https://twitter.com/spiderfoot)
+[](https://discord.gg/vyvztrG)
+
+**SpiderFoot** is an open source intelligence (OSINT) automation tool. It integrates with just about every data source available and utilises a range of methods for data analysis, making that data easy to navigate.
+
+SpiderFoot has an embedded web-server for providing a clean and intuitive web-based interface but can also be used completely via the command-line. It's written in **Python 3** and **MIT-licensed**.
+
+
+
+### FEATURES
+
+- Web based UI or CLI
+- Over 200 modules (see below)
+- Python 3.7+
+- YAML-configurable [correlation engine](/correlations/README.md) with [37 pre-defined rules](/correlations)
+- CSV/JSON/GEXF export
+- API key export/import
+- SQLite back-end for custom querying
+- Highly configurable
+- Fully documented
+- Visualisations
+- TOR integration for dark web searching
+- Dockerfile for Docker-based deployments
+- Can call other tools like DNSTwist, Whatweb, Nmap and CMSeeK
+- [Actively developed since 2012!](https://medium.com/@micallst/lessons-learned-from-my-10-year-open-source-project-4a4c8c2b4f64)
+
+### WANT MORE?
+
+Need more from SpiderFoot? Check out [SpiderFoot HX](https://www.spiderfoot.net/hx) for:
+- 100% Cloud-based and managed for you
+- Attack Surface Monitoring with change notifications by email, REST and Slack
+- Multiple targets per scan
+- Multi-user collaboration
+- Authenticated and 2FA
+- Investigations
+- Customer support
+- Third party tools pre-installed & configured
+- Drive it with a fully RESTful API
+- TOR integration built-in
+- Screenshotting
+- Bring your own Python SpiderFoot modules
+- Feed scan data to Splunk, ElasticSearch and REST endpoints
+
+See the full set of differences between SpiderFoot HX and the open source version [here](https://www.spiderfoot.net/open-source-vs-hx/).
+
+### USES
+
+SpiderFoot can be used offensively (e.g. in a red team exercise or penetration test) for reconnaissance of your target or defensively to gather information about what you or your organisation might have exposed over the Internet.
+
+You can target the following entities in a SpiderFoot scan:
+
+ - IP address
+ - Domain/sub-domain name
+ - Hostname
+ - Network subnet (CIDR)
+ - ASN
+ - E-mail address
+ - Phone number
+ - Username
+ - Person's name
+ - Bitcoin address
+
+SpiderFoot's 200+ modules feed each other in a publisher/subscriber model to ensure maximum data extraction to do things like:
+
+- [Host/sub-domain/TLD enumeration/extraction](https://asciinema.org/a/295912)
+- [Email address, phone number and human name extraction](https://asciinema.org/a/295947)
+- [Bitcoin and Ethereum address extraction](https://asciinema.org/a/295957)
+- [Check for susceptibility to sub-domain hijacking](https://asciinema.org/a/344377)
+- DNS zone transfers
+- [Threat intelligence and Blacklist queries](https://asciinema.org/a/295949)
+- API integration with [SHODAN](https://asciinema.org/a/127601), [HaveIBeenPwned](https://asciinema.org/a/128731), [GreyNoise](https://asciinema.org/a/295943), AlienVault, SecurityTrails, etc.
+- [Social media account enumeration](https://asciinema.org/a/295923)
+- [S3/Azure/Digitalocean bucket enumeration/scraping](https://asciinema.org/a/295941)
+- IP geo-location
+- Web scraping, web content analysis
+- [Image, document and binary file meta data analysis](https://asciinema.org/a/296274)
+- Dark web searches
+- [Port scanning and banner grabbing](https://asciinema.org/a/295939)
+- [Data breach searches](https://asciinema.org/a/296145)
+- So much more...
+
+### INSTALLING & RUNNING
+
+To install and run SpiderFoot, you need at least Python 3.7 and a number of Python libraries which you can install with `pip`. We recommend you install a packaged release since master will often have bleeding edge features and modules that aren't fully tested.
+
+#### Stable build (packaged release):
+
+```
+ wget https://github.com/smicallef/spiderfoot/archive/v4.0.tar.gz
+ tar zxvf v4.0.tar.gz
+ cd spiderfoot-4.0
+ pip3 install -r requirements.txt
+ python3 ./sf.py -l 127.0.0.1:5001
+```
+
+#### Development build (cloning git master branch):
+
+```
+ git clone https://github.com/smicallef/spiderfoot.git
+ cd spiderfoot
+ pip3 install -r requirements.txt
+ python3 ./sf.py -l 127.0.0.1:5001
+```
+
+Check out the [documentation](https://www.spiderfoot.net/documentation) and our [asciinema videos](https://asciinema.org/~spiderfoot) for more tutorials.
+
+### COMMUNITY
+
+Whether you're a contributor, user or just curious about SpiderFoot and OSINT in general, we'd love to have you join our community! SpiderFoot now has a [Discord server](https://discord.gg/vyvztrG) for seeking help from the community, requesting features or just general OSINT chit-chat.
+
+### WRITING CORRELATION RULES
+
+We have a comprehensive write-up and reference of the correlation rule-set introduced in SpiderFoot 4.0 [here](/correlations/README.md).
+
+Also take a look at the [template.yaml](/correlations/template.yaml) file for a walk through. The existing [37 rules](/correlations) are also quite readable and good as starting points for additional rules.
+
+### MODULES / INTEGRATIONS
+
+SpiderFoot has over 200 modules, most of which *don't require API keys*, and many of those that do require API keys *have a free tier*.
+
+| Name | Description | Type |
+|:---------| :-----------|:-------|
+[AbstractAPI](https://app.abstractapi.com/)|Look up domain, phone and IP address information from AbstractAPI.|Tiered API
+[abuse.ch](https://www.abuse.ch)|Check if a host/domain, IP address or netblock is malicious according to Abuse.ch.|Free API
+[AbuseIPDB](https://www.abuseipdb.com)|Check if an IP address is malicious according to AbuseIPDB.com blacklist.|Tiered API
+[Abusix Mail Intelligence](https://abusix.org/)|Check if a netblock or IP address is in the Abusix Mail Intelligence blacklist.|Tiered API
+Account Finder|Look for possible associated accounts on over 500 social and other websites such as Instagram, Reddit, etc.|Internal
+[AdBlock Check](https://adblockplus.org/)|Check if linked pages would be blocked by AdBlock Plus.|Tiered API
+[AdGuard DNS](https://adguard.com/)|Check if a host would be blocked by AdGuard DNS.|Free API
+[Ahmia](https://ahmia.fi/)|Search Tor 'Ahmia' search engine for mentions of the target.|Free API
+[AlienVault IP Reputation](https://cybersecurity.att.com/)|Check if an IP or netblock is malicious according to the AlienVault IP Reputation database.|Free API
+[AlienVault OTX](https://otx.alienvault.com/)|Obtain information from AlienVault Open Threat Exchange (OTX)|Tiered API
+[Amazon S3 Bucket Finder](https://aws.amazon.com/s3/)|Search for potential Amazon S3 buckets associated with the target and attempt to list their contents.|Free API
+[Apple iTunes](https://itunes.apple.com/)|Search Apple iTunes for mobile apps.|Free API
+[Archive.org](https://archive.org/)|Identifies historic versions of interesting files/pages from the Wayback Machine.|Free API
+[ARIN](https://www.arin.net/)|Queries ARIN registry for contact information.|Free API
+[Azure Blob Finder](https://azure.microsoft.com/en-in/services/storage/blobs/)|Search for potential Azure blobs associated with the target and attempt to list their contents.|Free API
+Base64 Decoder|Identify Base64-encoded strings in URLs, often revealing interesting hidden information.|Internal
+[BGPView](https://bgpview.io/)|Obtain network information from BGPView API.|Free API
+Binary String Extractor|Attempt to identify strings in binary content.|Internal
+[BinaryEdge](https://www.binaryedge.io/)|Obtain information from BinaryEdge.io Internet scanning systems, including breaches, vulnerabilities, torrents and passive DNS.|Tiered API
+[Bing (Shared IPs)](https://www.bing.com/)|Search Bing for hosts sharing the same IP.|Tiered API
+[Bing](https://www.bing.com/)|Obtain information from bing to identify sub-domains and links.|Tiered API
+Bitcoin Finder|Identify bitcoin addresses in scraped webpages.|Internal
+[Bitcoin Who's Who](https://bitcoinwhoswho.com/)|Check for Bitcoin addresses against the Bitcoin Who's Who database of suspect/malicious addresses.|Tiered API
+[BitcoinAbuse](https://www.bitcoinabuse.com/)|Check Bitcoin addresses against the bitcoinabuse.com database of suspect/malicious addresses.|Free API
+[Blockchain](https://www.blockchain.com/)|Queries blockchain.info to find the balance of identified bitcoin wallet addresses.|Free API
+[blocklist.de](http://www.blocklist.de/en/index.html)|Check if a netblock or IP is malicious according to blocklist.de.|Free API
+[BotScout](https://botscout.com/)|Searches BotScout.com's database of spam-bot IP addresses and e-mail addresses.|Tiered API
+[botvrij.eu](https://botvrij.eu/)|Check if a domain is malicious according to botvrij.eu.|Free API
+[BuiltWith](https://builtwith.com/)|Query BuiltWith.com's Domain API for information about your target's web technology stack, e-mail addresses and more.|Tiered API
+[C99](https://api.c99.nl/)|Queries the C99 API which offers various data (geo location, proxy detection, phone lookup, etc).|Commercial API
+[CallerName](http://callername.com/)|Lookup US phone number location and reputation information.|Free API
+[Censys](https://censys.io/)|Obtain host information from Censys.io.|Tiered API
+[Certificate Transparency](https://crt.sh/)|Gather hostnames from historical certificates in crt.sh.|Free API
+[CertSpotter](https://sslmate.com/certspotter/)|Gather information about SSL certificates from SSLMate CertSpotter API.|Tiered API
+[CINS Army List](https://cinsscore.com/)|Check if a netblock or IP address is malicious according to Collective Intelligence Network Security (CINS) Army list.|Free API
+[CIRCL.LU](https://www.circl.lu/)|Obtain information from CIRCL.LU's Passive DNS and Passive SSL databases.|Free API
+[CleanBrowsing.org](https://cleanbrowsing.org/)|Check if a host would be blocked by CleanBrowsing.org DNS content filters.|Free API
+[CleanTalk Spam List](https://cleantalk.org)|Check if a netblock or IP address is on CleanTalk.org's spam IP list.|Free API
+[Clearbit](https://clearbit.com/)|Check for names, addresses, domains and more based on lookups of e-mail addresses on clearbit.com.|Tiered API
+[CloudFlare DNS](https://www.cloudflare.com/)|Check if a host would be blocked by CloudFlare DNS.|Free API
+[CoinBlocker Lists](https://zerodot1.gitlab.io/CoinBlockerListsWeb/)|Check if a domain appears on CoinBlocker lists.|Free API
+[CommonCrawl](http://commoncrawl.org/)|Searches for URLs found through CommonCrawl.org.|Free API
+[Comodo Secure DNS](https://www.comodo.com/secure-dns/)|Check if a host would be blocked by Comodo Secure DNS.|Tiered API
+Company Name Extractor|Identify company names in any obtained data.|Internal
+Cookie Extractor|Extract Cookies from HTTP headers.|Internal
+Country Name Extractor|Identify country names in any obtained data.|Internal
+Credit Card Number Extractor|Identify Credit Card Numbers in any data|Internal
+[Crobat API](https://sonar.omnisint.io/)|Search Crobat API for subdomains.|Free API
+Cross-Referencer|Identify whether other domains are associated ('Affiliates') of the target by looking for links back to the target site(s).|Internal
+[CRXcavator](https://crxcavator.io/)|Search CRXcavator for Chrome extensions.|Free API
+Custom Threat Feed|Check if a host/domain, netblock, ASN or IP is malicious according to your custom feed.|Internal
+[CyberCrime-Tracker.net](https://cybercrime-tracker.net/)|Check if a host/domain or IP address is malicious according to CyberCrime-Tracker.net.|Free API
+[Debounce](https://debounce.io/)|Check whether an email is disposable|Free API
+[Dehashed](https://www.dehashed.com/)|Gather breach data from Dehashed API.|Commercial API
+[Digital Ocean Space Finder](https://www.digitalocean.com/products/spaces/)|Search for potential Digital Ocean Spaces associated with the target and attempt to list their contents.|Free API
+DNS Brute-forcer|Attempts to identify hostnames through brute-forcing common names and iterations.|Internal
+DNS Common SRV|Attempts to identify hostnames through brute-forcing common DNS SRV records.|Internal
+[DNS for Family](https://dnsforfamily.com/)|Check if a host would be blocked by DNS for Family.|Free API
+DNS Look-aside|Attempt to reverse-resolve the IP addresses next to your target to see if they are related.|Internal
+DNS Raw Records|Retrieves raw DNS records such as MX, TXT and others.|Internal
+DNS Resolver|Resolves hosts and IP addresses identified, also extracted from raw content.|Internal
+DNS Zone Transfer|Attempts to perform a full DNS zone transfer.|Internal
+[DNSDB](https://www.farsightsecurity.com)|Query FarSight's DNSDB for historical and passive DNS data.|Tiered API
+[DNSDumpster](https://dnsdumpster.com/)|Passive subdomain enumeration using HackerTarget's DNSDumpster|Free API
+[DNSGrep](https://opendata.rapid7.com/)|Obtain Passive DNS information from Rapid7 Sonar Project using DNSGrep API.|Free API
+[DroneBL](https://dronebl.org/)|Query the DroneBL database for open relays, open proxies, vulnerable servers, etc.|Free API
+[DuckDuckGo](https://duckduckgo.com/)|Query DuckDuckGo's API for descriptive information about your target.|Free API
+E-Mail Address Extractor|Identify e-mail addresses in any obtained data.|Internal
+[EmailCrawlr](https://emailcrawlr.com/)|Search EmailCrawlr for email addresses and phone numbers associated with a domain.|Tiered API
+[EmailFormat](https://www.email-format.com/)|Look up e-mail addresses on email-format.com.|Free API
+[EmailRep](https://emailrep.io/)|Search EmailRep.io for email address reputation.|Tiered API
+[Emerging Threats](https://rules.emergingthreats.net/)|Check if a netblock or IP address is malicious according to EmergingThreats.net.|Free API
+Error String Extractor|Identify common error messages in content like SQL errors, etc.|Internal
+Ethereum Address Extractor|Identify ethereum addresses in scraped webpages.|Internal
+[Etherscan](https://etherscan.io)|Queries etherscan.io to find the balance of identified ethereum wallet addresses.|Free API
+File Metadata Extractor|Extracts meta data from documents and images.|Internal
+[Flickr](https://www.flickr.com/)|Search Flickr for domains, URLs and emails related to the specified domain.|Free API
+[Focsec](https://focsec.com/)|Look up IP address information from Focsec.|Tiered API
+[FortiGuard Antispam](https://www.fortiguard.com/)|Check if an IP address is malicious according to FortiGuard Antispam.|Free API
+[Fraudguard](https://fraudguard.io/)|Obtain threat information from Fraudguard.io|Tiered API
+[F-Secure Riddler.io](https://riddler.io/)|Obtain network information from F-Secure Riddler.io API.|Commercial API
+[FullContact](https://www.fullcontact.com)|Gather domain and e-mail information from FullContact.com API.|Tiered API
+[FullHunt](https://fullhunt.io/)|Identify domain attack surface using FullHunt API.|Tiered API
+[Github](https://github.com/)|Identify associated public code repositories on Github.|Free API
+[GLEIF](https://search.gleif.org/)|Look up company information from Global Legal Entity Identifier Foundation (GLEIF).|Tiered API
+[Google Maps](https://cloud.google.com/maps-platform/)|Identifies potential physical addresses and latitude/longitude coordinates.|Tiered API
+[Google Object Storage Finder](https://cloud.google.com/storage)|Search for potential Google Object Storage buckets associated with the target and attempt to list their contents.|Free API
+[Google SafeBrowsing](https://developers.google.com/safe-browsing/v4/lookup-api)|Check if the URL is included on any of the Safe Browsing lists.|Free API
+[Google](https://developers.google.com/custom-search)|Obtain information from the Google Custom Search API to identify sub-domains and links.|Tiered API
+[Gravatar](https://secure.gravatar.com/)|Retrieve user information from Gravatar API.|Free API
+[Grayhat Warfare](https://buckets.grayhatwarfare.com/)|Find bucket names matching the keyword extracted from a domain from Grayhat API.|Tiered API
+[Greensnow](https://greensnow.co/)|Check if a netblock or IP address is malicious according to greensnow.co.|Free API
+[grep.app](https://grep.app/)|Search grep.app API for links and emails related to the specified domain.|Free API
+[GreyNoise Community](https://greynoise.io/)|Obtain IP enrichment data from GreyNoise Community API|Tiered API
+[GreyNoise](https://greynoise.io/)|Obtain IP enrichment data from GreyNoise|Tiered API
+[HackerOne (Unofficial)](http://www.nobbd.de/)|Check external vulnerability scanning/reporting service h1.nobbd.de to see if the target is listed.|Free API
+[HackerTarget](https://hackertarget.com/)|Search HackerTarget.com for hosts sharing the same IP.|Free API
+Hash Extractor|Identify MD5 and SHA hashes in web content, files and more.|Internal
+[HaveIBeenPwned](https://haveibeenpwned.com/)|Check HaveIBeenPwned.com for hacked e-mail addresses identified in breaches.|Commercial API
+Hosting Provider Identifier|Find out if any IP addresses identified fall within known 3rd party hosting ranges, e.g. Amazon, Azure, etc.|Internal
+[Host.io](https://host.io)|Obtain information about domain names from host.io.|Tiered API
+Human Name Extractor|Attempt to identify human names in fetched content.|Internal
+[Hunter.io](https://hunter.io/)|Check for e-mail addresses and names on hunter.io.|Tiered API
+[Hybrid Analysis](https://www.hybrid-analysis.com)|Search Hybrid Analysis for domains and URLs related to the target.|Free API
+IBAN Number Extractor|Identify International Bank Account Numbers (IBANs) in any data.|Internal
+[Iknowwhatyoudownload.com](https://iknowwhatyoudownload.com/en/peer/)|Check iknowwhatyoudownload.com for IP addresses that have been using torrents.|Tiered API
+[IntelligenceX](https://intelx.io/)|Obtain information from IntelligenceX about identified IP addresses, domains, e-mail addresses and phone numbers.|Tiered API
+Interesting File Finder|Identifies potential files of interest, e.g. office documents, zip files.|Internal
+[Internet Storm Center](https://isc.sans.edu)|Check if an IP address is malicious according to SANS ISC.|Free API
+[ipapi.co](https://ipapi.co/)|Queries ipapi.co to identify geolocation of IP Addresses using ipapi.co API|Tiered API
+[ipapi.com](https://ipapi.com/)|Queries ipapi.com to identify geolocation of IP Addresses using ipapi.com API|Tiered API
+[IPInfo.io](https://ipinfo.io)|Identifies the physical location of IP addresses identified using ipinfo.io.|Tiered API
+[IPQualityScore](https://www.ipqualityscore.com/)|Determine if target is malicious using IPQualityScore API|Tiered API
+[ipregistry](https://ipregistry.co/)|Query the ipregistry.co database for reputation and geo-location.|Tiered API
+[ipstack](https://ipstack.com/)|Identifies the physical location of IP addresses identified using ipstack.com.|Tiered API
+[JsonWHOIS.com](https://jsonwhois.com)|Search JsonWHOIS.com for WHOIS records associated with a domain.|Tiered API
+Junk File Finder|Looks for old/temporary and other similar files.|Internal
+[Keybase](https://keybase.io/)|Obtain additional information about domain names and identified usernames.|Free API
+[Koodous](https://koodous.com/apks/)|Search Koodous for mobile apps.|Tiered API
+[LeakIX](https://leakix.net/)|Search LeakIX for host data leaks, open ports, software and geoip.|Free API
+[Leak-Lookup](https://leak-lookup.com/)|Searches Leak-Lookup.com's database of breaches.|Free API
+[Maltiverse](https://maltiverse.com)|Obtain information about any malicious activities involving IP addresses|Free API
+[MalwarePatrol](https://www.malwarepatrol.net/)|Searches malwarepatrol.net's database of malicious URLs/IPs.|Tiered API
+[MetaDefender](https://metadefender.opswat.com/)|Search MetaDefender API for IP address and domain IP reputation.|Tiered API
+[Mnemonic PassiveDNS](https://www.mnemonic.no)|Obtain Passive DNS information from PassiveDNS.mnemonic.no.|Free API
+[multiproxy.org Open Proxies](https://multiproxy.org/)|Check if an IP address is an open proxy according to multiproxy.org open proxy list.|Free API
+[MySpace](https://myspace.com/)|Gather username and location from MySpace.com profiles.|Free API
+[NameAPI](https://www.nameapi.org/)|Check whether an email is disposable|Tiered API
+[NetworksDB](https://networksdb.io/)|Search NetworksDB.io API for IP address and domain information.|Tiered API
+[NeutrinoAPI](https://www.neutrinoapi.com/)|Search NeutrinoAPI for phone location information, IP address information, and host reputation.|Tiered API
+[numverify](http://numverify.com/)|Lookup phone number location and carrier information from numverify.com.|Tiered API
+[Onion.link](https://onion.link/)|Search Tor 'Onion City' search engine for mentions of the target domain using Google Custom Search.|Free API
+[Onionsearchengine.com](https://as.onionsearchengine.com)|Search Tor onionsearchengine.com for mentions of the target domain.|Free API
+[Onyphe](https://www.onyphe.io)|Check Onyphe data (threat list, geo-location, pastries, vulnerabilities) about a given IP.|Tiered API
+[Open Bug Bounty](https://www.openbugbounty.org/)|Check external vulnerability scanning/reporting service openbugbounty.org to see if the target is listed.|Free API
+[OpenCorporates](https://opencorporates.com)|Look up company information from OpenCorporates.|Tiered API
+[OpenDNS](https://www.opendns.com/)|Check if a host would be blocked by OpenDNS.|Free API
+[OpenNIC DNS](https://www.opennic.org/)|Resolves host names in the OpenNIC alternative DNS system.|Free API
+[OpenPhish](https://openphish.com/)|Check if a host/domain is malicious according to OpenPhish.com.|Free API
+[OpenStreetMap](https://www.openstreetmap.org/)|Retrieves latitude/longitude coordinates for physical addresses from OpenStreetMap API.|Free API
+Page Information|Obtain information about web pages (do they take passwords, do they contain forms, etc.)|Internal
+[PasteBin](https://pastebin.com/)|PasteBin search (via Google Search API) to identify related content.|Tiered API
+PGP Key Servers|Look up domains and e-mail addresses in PGP public key servers.|Internal
+[PhishStats](https://phishstats.info/)|Check if a netblock or IP address is malicious according to PhishStats.|Free API
+[PhishTank](https://phishtank.com/)|Check if a host/domain is malicious according to PhishTank.|Free API
+Phone Number Extractor|Identify phone numbers in scraped webpages.|Internal
+Port Scanner - TCP|Scans for commonly open TCP ports on Internet-facing systems.|Internal
+[Project Honey Pot](https://www.projecthoneypot.org/)|Query the Project Honey Pot database for IP addresses.|Free API
+[ProjectDiscovery Chaos](https://chaos.projectdiscovery.io)|Search for hosts/subdomains using chaos.projectdiscovery.io|Commercial API
+[Psbdmp](https://psbdmp.cc/)|Check psbdmp.cc (PasteBin Dump) for potentially hacked e-mails and domains.|Free API
+[Pulsedive](https://pulsedive.com/)|Obtain information from Pulsedive's API.|Tiered API
+[PunkSpider](https://punkspider.io/)|Check the QOMPLX punkspider.io service to see if the target is listed as vulnerable.|Free API
+[Quad9](https://quad9.net/)|Check if a host would be blocked by Quad9 DNS.|Free API
+[ReverseWhois](https://www.reversewhois.io/)|Reverse Whois lookups using reversewhois.io.|Free API
+[RIPE](https://www.ripe.net/)|Queries the RIPE registry (includes ARIN data) to identify netblocks and other info.|Free API
+[RiskIQ](https://community.riskiq.com/)|Obtain information from RiskIQ's (formerly PassiveTotal) Passive DNS and Passive SSL databases.|Tiered API
+[Robtex](https://www.robtex.com/)|Search Robtex.com for hosts sharing the same IP.|Free API
+[searchcode](https://searchcode.com/)|Search searchcode for code repositories mentioning the target domain.|Free API
+[SecurityTrails](https://securitytrails.com/)|Obtain Passive DNS and other information from SecurityTrails|Tiered API
+[Seon](https://seon.io/)|Queries seon.io to gather intelligence about IP Addresses, email addresses, and phone numbers|Commercial API
+[SHODAN](https://www.shodan.io/)|Obtain information from SHODAN about identified IP addresses.|Tiered API
+Similar Domain Finder|Search various sources to identify similar looking domain names, for instance squatted domains.|Internal
+[Skymem](http://www.skymem.info/)|Look up e-mail addresses on Skymem.|Free API
+[SlideShare](https://www.slideshare.net)|Gather name and location from SlideShare profiles.|Free API
+[Snov](https://snov.io/)|Gather available email IDs from identified domains|Tiered API
+[Social Links](https://sociallinks.io/)|Queries SocialLinks.io to gather intelligence from social media platforms and dark web.|Commercial API
+[Social Media Profile Finder](https://developers.google.com/custom-search)|Tries to discover the social media profiles for human names identified.|Tiered API
+Social Network Identifier|Identify presence on social media networks such as LinkedIn, Twitter and others.|Internal
+[SORBS](http://www.sorbs.net/)|Query the SORBS database for open relays, open proxies, vulnerable servers, etc.|Free API
+[SpamCop](https://www.spamcop.net/)|Check if a netblock or IP address is in the SpamCop database.|Free API
+[Spamhaus Zen](https://www.spamhaus.org/)|Check if a netblock or IP address is in the Spamhaus Zen database.|Free API
+[spur.us](https://spur.us/)|Obtain information about any malicious activities involving IP addresses found|Commercial API
+[SpyOnWeb](http://spyonweb.com/)|Search SpyOnWeb for hosts sharing the same IP address, Google Analytics code, or Google Adsense code.|Tiered API
+SSL Certificate Analyzer|Gather information about SSL certificates used by the target's HTTPS sites.|Internal
+[StackOverflow](https://www.stackexchange.com)|Search StackOverflow for any mentions of a target domain. Returns potentially related information.|Tiered API
+[Steven Black Hosts](https://github.com/StevenBlack/hosts)|Check if a domain is malicious (malware or adware) according to Steven Black Hosts list.|Free API
+Strange Header Identifier|Obtain non-standard HTTP headers returned by web servers.|Internal
+Subdomain Takeover Checker|Check if affiliated subdomains are vulnerable to takeover.|Internal
+[Sublist3r PassiveDNS](https://api.sublist3r.com)|Passive subdomain enumeration using Sublist3r's API|Free API
+[SURBL](http://www.surbl.org/)|Check if a netblock, IP address or domain is in the SURBL blacklist.|Free API
+[Talos Intelligence](https://talosintelligence.com/)|Check if a netblock or IP address is malicious according to TalosIntelligence.|Free API
+[TextMagic](https://www.textmagic.com/)|Obtain phone number type from TextMagic API|Tiered API
+[Threat Jammer](https://threatjammer.com)|Check if an IP address is malicious according to ThreatJammer.com|Tiered API
+[ThreatCrowd](https://www.threatcrowd.org)|Obtain information from ThreatCrowd about identified IP addresses, domains and e-mail addresses.|Free API
+[ThreatFox](https://threatfox.abuse.ch)|Check if an IP address is malicious according to ThreatFox.|Free API
+[ThreatMiner](https://www.threatminer.org/)|Obtain information from ThreatMiner's database for passive DNS and threat intelligence.|Free API
+TLD Searcher|Search all Internet TLDs for domains with the same name as the target (this can be very slow.)|Internal
+[Tool - CMSeeK]([https://github.com/Tuhinshubhra/CMSeeK](https://github.com/Tuhinshubhra/CMSeeK))|Identify what Content Management System (CMS) might be used.|Tool
+[Tool - DNSTwist]([https://github.com/elceef/dnstwist](https://github.com/elceef/dnstwist))|Identify bit-squatting, typo and other similar domains to the target using a local DNSTwist installation.|Tool
+[Tool - nbtscan]([http://www.unixwiz.net/tools/nbtscan.html](http://www.unixwiz.net/tools/nbtscan.html))|Scans for open NETBIOS nameservers on your target's network.|Tool
+[Tool - Nmap]([https://nmap.org/](https://nmap.org/))|Identify what Operating System might be used.|Tool
+[Tool - Nuclei]([https://nuclei.projectdiscovery.io/](https://nuclei.projectdiscovery.io/))|Fast and customisable vulnerability scanner.|Tool
+[Tool - onesixtyone]([https://github.com/trailofbits/onesixtyone](https://github.com/trailofbits/onesixtyone))|Fast scanner to find publicly exposed SNMP services.|Tool
+[Tool - Retire.js]([http://retirejs.github.io/retire.js/](http://retirejs.github.io/retire.js/))|Scanner detecting the use of JavaScript libraries with known vulnerabilities|Tool
+[Tool - snallygaster]([https://github.com/hannob/snallygaster](https://github.com/hannob/snallygaster))|Finds file leaks and other security problems on HTTP servers.|Tool
+[Tool - testssl.sh]([https://testssl.sh](https://testssl.sh))|Identify various TLS/SSL weaknesses, including Heartbleed, CRIME and ROBOT.|Tool
+[Tool - TruffleHog]([https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog))|Searches through git repositories for high entropy strings and secrets, digging deep into commit history.|Tool
+[Tool - WAFW00F]([https://github.com/EnableSecurity/wafw00f](https://github.com/EnableSecurity/wafw00f))|Identify what web application firewall (WAF) is in use on the specified website.|Tool
+[Tool - Wappalyzer]([https://www.wappalyzer.com/](https://www.wappalyzer.com/))|Wappalyzer indentifies technologies on websites.|Tool
+[Tool - WhatWeb]([https://github.com/urbanadventurer/whatweb](https://github.com/urbanadventurer/whatweb))|Identify what software is in use on the specified website.|Tool
+[TOR Exit Nodes](https://metrics.torproject.org/)|Check if an IP adddress or netblock appears on the Tor Metrics exit node list.|Free API
+[TORCH](https://torchsearch.wordpress.com/)|Search Tor 'TORCH' search engine for mentions of the target domain.|Free API
+[Trashpanda](https://got-hacked.wtf)|Queries Trashpanda to gather intelligence about mentions of target in pastesites|Tiered API
+[Trumail](https://trumail.io/)|Check whether an email is disposable|Free API
+[Twilio](https://www.twilio.com/)|Obtain information from Twilio about phone numbers. Ensure you have the Caller Name add-on installed in Twilio.|Tiered API
+[Twitter](https://twitter.com/)|Gather name and location from Twitter profiles.|Free API
+[UCEPROTECT](http://www.uceprotect.net/)|Check if a netblock or IP address is in the UCEPROTECT database.|Free API
+[URLScan.io](https://urlscan.io/)|Search URLScan.io cache for domain information.|Free API
+[Venmo](https://venmo.com/)|Gather user information from Venmo API.|Free API
+[ViewDNS.info](https://viewdns.info/)|Identify co-hosted websites and perform reverse Whois lookups using ViewDNS.info.|Tiered API
+[VirusTotal](https://www.virustotal.com/)|Obtain information from VirusTotal about identified IP addresses.|Tiered API
+[VoIP Blacklist (VoIPBL)](https://voipbl.org/)|Check if an IP address or netblock is malicious according to VoIP Blacklist (VoIPBL).|Free API
+[VXVault.net](http://vxvault.net/)|Check if a domain or IP address is malicious according to VXVault.net.|Free API
+Web Analytics Extractor|Identify web analytics IDs in scraped webpages and DNS TXT records.|Internal
+Web Framework Identifier|Identify the usage of popular web frameworks like jQuery, YUI and others.|Internal
+Web Server Identifier|Obtain web server banners to identify versions of web servers being used.|Internal
+Web Spider|Spidering of web-pages to extract content for searching.|Internal
+[WhatCMS](https://whatcms.org/)|Check web technology using WhatCMS.org API.|Tiered API
+[Whoisology](https://whoisology.com/)|Reverse Whois lookups using Whoisology.com.|Commercial API
+Whois|Perform a WHOIS look-up on domain names and owned netblocks.|Internal
+[Whoxy](https://www.whoxy.com/)|Reverse Whois lookups using Whoxy.com.|Commercial API
+[WiGLE](https://wigle.net/)|Query WiGLE to identify nearby WiFi access points.|Free API
+[Wikileaks](https://wikileaks.org/)|Search Wikileaks for mentions of domain names and e-mail addresses.|Free API
+[Wikipedia Edits](https://www.wikipedia.org/)|Identify edits to Wikipedia articles made from a given IP address or username.|Free API
+[XForce Exchange](https://exchange.xforce.ibmcloud.com/)|Obtain IP reputation and passive DNS information from IBM X-Force Exchange.|Tiered API
+[Yandex DNS](https://yandex.com/)|Check if a host would be blocked by Yandex DNS.|Free API
+[Zetalytics](https://zetalytics.com/)|Query the Zetalytics database for hosts on your target domain(s).|Tiered API
+[ZoneFile.io](https://zonefiles.io)|Search ZoneFiles.io Domain query API for domain information.|Tiered API
+[Zone-H Defacement Check](https://zone-h.org/)|Check if a hostname/domain appears on the zone-h.org 'special defacements' RSS feed.|Free API
+
+### DOCUMENTATION
+
+Read more at the [project website](https://www.spiderfoot.net/r.php?u=aHR0cHM6Ly93d3cuc3BpZGVyZm9vdC5uZXQv&s=os_gh), including more complete documentation, blog posts with tutorials/guides, plus information about [SpiderFoot HX](https://www.spiderfoot.net/r.php?u=aHR0cHM6Ly93d3cuc3BpZGVyZm9vdC5uZXQvaHgvCg==&s=os_gh).
+
+Latest updates announced on [Twitter](https://twitter.com/spiderfoot).
diff --git a/spiderfoot/THANKYOU b/spiderfoot/THANKYOU
new file mode 100644
index 0000000000000000000000000000000000000000..87102cb3d9fe9c8384d05cae5782d89105831563
--- /dev/null
+++ b/spiderfoot/THANKYOU
@@ -0,0 +1,61 @@
+These people are owed some credit for their contributions to SpiderFoot, be it
+bug fixes or new functionality. Thank you!
+
+- Brendan Coles (https://github.com/bcoles)
+ - Second highest contributor to the project
+ - Tons of modules, fixes and established the whole testing framework
+ - Too many contributions to list here, see https://github.com/smicallef/spiderfoot/pulls?q=is%3Apr+author%3Abcoles+is%3Aclosed
+
+- Krishnasis Mandal (https://github.com/krishnasism)
+ - Many modules, see https://github.com/smicallef/spiderfoot/pulls?q=is%3Apr+author%3Akrishnasism+is%3Aclosed
+
+- Steve Bate (https://github.com/steve-bate)
+ - Multiple bug fixes, performance and quality improvements
+
+- fallingcubes (https://github.com/fallingcubes)
+ - Use of multiprocessing instead of threading for running multiple scans simultaneously
+
+- Counter Intrusive Technologies (https://github.com/counterintrusive)
+ - sfp_citadel updates
+
+- Dhiraj Mishra (https://github.com/RootUp)
+ - Created the sfp_h1nobbdde module
+
+- Chris Weber (http://www.casaba.com/blog/author/chris/)
+ - Many recommendations for improvement
+
+- Henri Salo (https://github.com/fgeek)
+ - Identified XSS issues (issue #29)
+
+- MarioVilas (https://github.com/MarioVilas)
+ - Contributed a fix for CSV exports (issue #35)
+
+- johnnykv (https://github.com/johnnykv)
+ - Contributed improved pip instructions
+
+- Russ McRee (@holisticinfosec)
+ - Identified XSS/CSRF issues
+
+- Andrea De Pasquale (https://github.com/adepasquale)
+ - Cache directory fix
+
+- Viyat Bhalodia (https://github.com/delta24)
+ - Prettied up README.md
+
+- Gormogon (https://github.com/Gormogon)
+ - Huge code clean up for PEP 8 compliance
+
+- Lin Zhemin (https://github.com/miaoski)
+ - Added the ability to use a configurable document root
+
+- Micah Hoffman (https://github.com/WebBreacher)
+ - Comprehensive list of URLs for identifying account usage in modules/sfp_accounts.py
+
+- Michael Pellon (https://github.com/mpellon)
+ - Providing a Dockerfile
+
+- HackershubNL (https://github.com/HackershubNL)
+ - Contributions towards authentication functionality
+
+- Mathew Woodyard (https://github.com/woodrad)
+ - Bad Packets module improvements
diff --git a/spiderfoot/VERSION b/spiderfoot/VERSION
new file mode 100644
index 0000000000000000000000000000000000000000..f944fd5be7f90f6623020318585f656ab1e90cb3
--- /dev/null
+++ b/spiderfoot/VERSION
@@ -0,0 +1 @@
+SpiderFoot 4.0.0
diff --git a/spiderfoot/correlations/README.md b/spiderfoot/correlations/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..47eff34af271237ad4869cc64c5490480c11552b
--- /dev/null
+++ b/spiderfoot/correlations/README.md
@@ -0,0 +1,194 @@
+## Background
+
+SpiderFoot’s goal is to automate OSINT collection and analysis to the greatest extent possible. Since its inception, SpiderFoot has heavily focused on automating OSINT collection and entity extraction, but the automation of common analysis tasks -- beyond some reporting and visualisations -- has been left entirely to the user. The meant that the strength of SpiderFoot's data collection capabilities has sometimes been its weakness since with so much data collected, users have often needed to export it and use other tools to weed out data of interest.
+
+## Introducing Correlations
+
+We started tackling this analysis gap with the launch of SpiderFoot HX in 2019 through the introduction of the "Correlations" feature. This feature was represented by some 30 "correlation rules" that ran with each scan, analyzing data and presenting results reflecting SpiderFoot's opinionated view on what may be important or interesting. Here are a few of those rules as examples:
+* Hosts/IPs reported as malicious by multiple data sources
+* Outlier web servers (can be an indication of shadow IT)
+* Databases exposed on the Internet
+* Open ports revealing software versions
+* and many more.
+
+With the release of SpiderFoot 4.0 we wanted to bring this capability from SpiderFoot HX to the community, but also re-imagine it at the same time so that the community might not simply run rules we provide, but also write their own correlation rules and contribute them back. We also hope that just as with modules, we see a long list of contributions made in the years ahead so that all may benefit.
+
+With that said, let's get into what these rules look like and how to write one.
+
+## Key concepts
+
+### YAML
+The rules themselves are written in YAML. Why YAML? It’s easy to read, write, allows for comments and is increasingly commonplace in many modern tools.
+
+### Rule structure
+The simplest way to think of a SpiderFoot correlation rule is like a simple database query that consists of a few sections:
+1. Defining the rule itself (`id`, `version` and `meta` sections).
+2. Stating what you'd like to extract from the scan results (`collections` section).
+3. Grouping that data in some way (`aggregation` section; optional).
+3. Performing some analysis over that data in some way (`analysis` section; optional).
+4. Presenting the results (`headline` section).
+
+### Example rule
+Here's an example rule that looks at SpiderFoot scan results for data revealing open TCP ports where the banner (the data returned upon connecting to the port) reports a software version. It does so by applying some regular expressions to the content of `TCP_PORT_OPEN_BANNER` data elements, filtering out some false positives and then grouping the results by the banner itself so that one correlation result is created per banner revealing a version:
+
+```yaml
+id: open_port_version
+version: 1
+meta:
+ name: Open TCP port reveals version
+ description: >
+ A possible software version has been revealed on an open port. Such
+ information may reveal the use of old/unpatched software used by
+ the target.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: TCP_PORT_OPEN_BANNER
+ - method: regex
+ field: data
+ value: .*[0-9]\.[0-9].*
+ - method: regex
+ field: data
+ value: not .*Mime-Version.*
+ - method: regex
+ field: data
+ value: not .*HTTP/1.*
+aggregation:
+ field: data
+headline: "Software version revealed on open port: {data}"
+```
+
+### The outcome
+To show this in practice, we can run a simple scan against a target, in this case focusing on performing a port scan:
+
+```
+-> # python3.9 ./sf.py -s www.binarypool.com -m sfp_dnsresolve,sfp_portscan_tcp
+2022-04-06 08:14:58,476 [INFO] sflib : Scan [94EB5F0B] for 'www.binarypool.com' initiated.
+...
+sfp_portscan_tcp Open TCP Port Banner SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
+...
+2022-04-06 08:15:23,110 [INFO] correlation : New correlation [open_port_version]: Software version revealed on open port: SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
+2022-04-06 08:15:23,244 [INFO] sflib : Scan [94EB5F0B] completed.
+```
+We can see above that a port was found to be open by the `sfp_portscan_tcp` module, and it happens to include a version. The correlation rule `open_port_version` picked this up and reported it. This is also visible in the web interface:
+
+
+
+**NOTE:** Rules will only succeed if relevant data exists in your scan results in the first place. In other words, correlation rules analyze scan data, they don't collect data from targets.
+
+### How it works
+In short, SpiderFoot translates the YAML rules into a combination queries against the backend database of scan results and Python logic to filter and group the results, creating "correlation results" in the SpiderFoot database. These results can be viewed in the SpiderFot web interface or from the SpiderFoot CLI. You can also query them directly out of the SQLite database if you like (they are in the `tbl_scan_correlation_results` table, and the `tbl_scan_correlation_results_events` table maps the events (data elements) to the correlation result).
+
+### The rules
+
+Each rule exists as a YAML file within the `/correlations` folder in the SpiderFoot installation path. Here you can see a list of rules in 4.0, which we hope to grow over time:
+
+```sh
+cert_expired.yaml host_only_from_certificatetransparency.yaml outlier_ipaddress.yaml
+cloud_bucket_open.yaml http_errors.yaml outlier_registrar.yaml
+cloud_bucket_open_related.yaml human_name_in_whois.yaml outlier_webserver.yaml
+data_from_base64.yaml internal_host.yaml remote_desktop_exposed.yaml
+data_from_docmeta.yaml multiple_malicious.yaml root_path_needs_auth.yaml
+database_exposed.yaml multiple_malicious_affiliate.yaml stale_host.yaml
+dev_or_test_system.yaml multiple_malicious_cohost.yaml strong_affiliate_certs.yaml
+dns_zone_transfer_possible.yaml name_only_from_pasteleak_site.yaml strong_similardomain_crossref.yaml
+egress_ip_from_wikipedia.yaml open_port_version.yaml template.yaml
+email_in_multiple_breaches.yaml outlier_cloud.yaml vulnerability_critical.yaml
+email_in_whois.yaml outlier_country.yaml vulnerability_high.yaml
+email_only_from_pasteleak_site.yaml outlier_email.yaml vulnerability_mediumlow.yaml
+host_only_from_bruteforce.yaml outlier_hostname.yaml
+```
+### Rule components
+
+The rules themselves are broken down into the following components:
+
+**Meta**: Describes the rule itself so that humans understand what the rule does and the risk level of any results. This information is used mostly in the web interface and CLI.
+
+**Collections**: A collection represents a set of data pulled from scan results, to be used in later aggregation and analysis stages. Each rule can have multiple collections.
+
+**Aggregations**: An aggregation buckets the collected data into groups for analysis in distinct groups of data elements.
+
+**Analysis**: Analysis performs (you guessed it) analysis on the data to whittle down the data elements to what ultimately gets reported. For example, the analysis stage may look only for cases where the data field is repeated in the data set, indicating it was found multiple times and therefore discarding any only appearing once.
+
+**Headline**: The headline represents the actual correlation title that summarizes what was found. You can think of this as equivalent to a meal name (beef stew), and all the data elements as being the ingredients (beef, tomatoes, onions, etc.).
+
+### Creating a rule
+
+To create your own rule, simply copy the `template.yaml` file in the `correlations` folder to a meaningful name that matches the ID you intend to provide it, e.g. `aws_cloud_usage.yaml` and edit the rule to fit your needs. Save it and re-start SpiderFoot for the rule to be loaded. If there are any syntax errors, SpiderFoot will abort at startup and (hopefully) give you enough information to know where the error is.
+
+The `template.yaml` file is also a good next point of reference to better understand the structure of the rules and how to use them. We also recommend taking a look through the actual rules themselves to see the concepts in practice.
+
+## Rule Reference
+
+**id**: The internal ID for this rule, which needs to match the filename.
+
+**version**: The rule syntax version. This must be `1` for now.
+
+**meta**: This section contains a few important fields used to describe the rule.
+
+ * **name**: A short, human readable name for the rule.
+ * **description**: A longer (can be multi-paragraph) description of the rule.
+ * **risk**: The risk level represented by this rule's findings. Can be `INFO`, `LOW`, `MEDIUM`, `HIGH`.
+
+**collection**: A correlation rule contains one or more `collect` blocks. Each `collect` block contains one or more `method` blocks telling SpiderFoot what criteria to use for extracting data from the database and how to filter it down.
+ * **collect**: Technically, the first `method` block in each `collect` block is what actually pulls data from the database, and each subsequent `method` refines that dataset down to what you’re seeking. You may have multiple `collect` blocks overall but the rule remains that within each `collect`, the first `method` pulls data from the database and subsequent `method` blocks within the `collect` refine that data.
+
+ * **method**: Each `method` block tells SpiderFoot how to collect and refine data. Each `collect` must contain at least one `method` block. Valid methods are `exact` for performing an exact match of the chosen `field` to the supplied `value`, or `regex` to perform regular expression matching.
+
+ * **field**: Each `method` block has a `field` upon which the matching should be performed. Valid fields are `type` (e.g. `INTERNET_NAME`), `module` (e.g. `sfp_whois`) and `data`, which would be the value of the data element (e.g. in case of an `INTERNET_NAME`, the `data` would be the hostname). After the first `method` block, you can also prefix the field with `source.`, `child.` or `entity.` to refer to the fields of the source, children or relevant entities of the collected data, respectively (see `multiple_malicious.yaml` and `data_from_docmeta.yaml` as examples of this approach).
+
+ * **value**: Here you supply the value or values you wish to match against the field you supplied in `field`. If your `method` was `regex`, this would be a regular expression.
+
+**aggregation**: With all the data elements in their collections, you can now aggregate them into buckets for further analysis or immediately generate results from the rule. While the collection phase is about obtaining the data from the database and filtering down to data of interest, the aggregation phase is about grouping that data in different ways in order to support analysis and/or grouping reported results.
+
+Aggregation simply iterates through the data elements in each collection and places them into groups based on the `field` specified. For instance if you pick the `type` field, you’ll end up with data elements with the same `type` field grouped together. The purpose of this grouping is two-fold: to support the analysis stage, or if you don’t have the analysis stage, it’s how your correlation results will be grouped for the user.
+ * **field**: The `field` defines how you'd like your data elements grouped together. Just like the `field` option in `method` blocks above, you may prefix the field with `source.`, `child.` or `entity.` to apply the aggregation on those fields of the data element instead. For example, if you intended to look for multiple occurrences of a hostname, you would specify `data` here as that field, since you want to count the number of times the value of the `data` field appears.
+
+**analysis**
+The analysis section applies (you guessed it) some analysis to the aggregated results or collections directly if you didn’t perform any aggregation, and drops candidate results if they fail this stage. Various analysis `method` types exist, and each takes different options, described below.
+
+ * **method**:
+ * **threshold**: Drop any collection/aggregation of data elements that do not meet the defined thresholds. You would use this analysis rule when wanting to generate a result only when a data element has appeared more or less than a limit specified, for instance reporting when an email address is reported just once, or more than 100 times.
+ * **field**: The field you want to apply the threshold too. As per above, you can use `child.`, `source.` and `entity.` field prefixes here too.
+ * **count_unique_only**: By default the threshold is applied to the `field` specified on all data elements, but by setting `count_unique_only` to `true`, you can limit the threshold to only unique values in the `field` specified, so as not to also count duplicates.
+ * **minimum**: The minimum number of data elements that must appear within the collection or aggregation.
+ * **maximum**: The maximum number of data elements that must appear within the collection or aggregation.
+ * **outlier**: Only keep outliers within any collection/aggregation of data elements.
+ * **maximum_percent**: The maximum percentage of the overall results that an aggregation can represent. This method requires that you have performed an aggregation on a certain field in order to function. For example, if you aggregate on the `data` field of your collections, and one of those buckets contains less than 10% of the overall volume, it will be reported as an outlier.
+ * **noisy_percent**: By default this is `10`, meaning that if the average percentage every bucket is below 10%, don't report outliers since the dataset is anomalous.
+ * **first_collection_only**: Only keep data elements that appeared in the first collection but not any others. For example, this is handy for finding cases where data was found from one or several data sources but not others.
+ * **field**: The field you want to use for looking up between collections.
+ * **match_all_to_first_collection**: Only keep data elements that have matched in some way to the first collection. This requires an aggregation to have been performed, as the field used for aggregation is what will be used for checking for a match.
+ * **match_method**: How to match between all collections and the first collection. Options are `contains` (simple wildcard match), `exact` and `subnet` which reports a match if the expected field may contain an IP address that is within the first collection field containing a subnet.
+
+**headline**
+After all data elements have been collected, filtered down, aggregated and analyzed, if data elements are remaining, these are what we call "correlation results" -> the results of your correlation rule. These need a "headline" to summarize the findings, which you can define here. To place any value from your data into the headline, you must enclose the field in `{}`, e.g. `{entity.data}`. There are two ways to write a `headline` rule. The typical way is to simply have `headline: titletexthere`, or have it as a block, in which case you can be more granular about how the correlation results are published:
+
+* **text**: The headline text, as described above.
+* **publish_collections**: The collection you wish to have associated with the correlation result. This is not often needed, but more in combination with the `match_all_to_first_collection` analysis rule in case your first collection is only used as a reference point and not actually contain any data elements you wish to publish with this correlation result. Take a look at the `egress_ip_from_wikipedia.yaml` rule for an example of this used in practice.
+
+### A note about `child.`, `source.` and `entity.` field prefixes
+
+Every data element pulled in the first `match` rule in a collection will also have any children (data resulting from that data element), the source (the data element that this data element was generated from) and entity (the source, or source of source, etc. that was an entity like IP address, domain, etc.). This enables you to prefix subsequent (and only subsequent!) match block field names with `child.`, `source.` and `entity.` if you wish to match based on those fields. These prefixes, as shown above, can also be used in the `aggregation`, `analysis` and `headline` sections too.
+
+It is vital to note that these prefixes **always** are in reference to the first `match` block within each `collect` block, since every subsequent `match` block is always a refinement of the first `match` block.
+
+This can be complicated, so let's use an example to illustrate. Let's say your scan has found a hostname (a data element type of `INTERNET_NAME`) of `foo`, and it found that within some webpage content (a data element type of `TARGET_WEB_CONTENT`) of "This is some web content: foo", which was from a URL (data element type of `LINKED_URL_INTERNAL`) of "https://bar/page.html", which was from another host named `bar`. Here's the data discovery path:
+
+`bar` [`INTERNET_NAME`] -> `https://bar/page.html` [`LINKED_URL_INTERNAL`] -> `This is some web content: foo` [`TARGET_WEB_CONTENT`] -> `foo` [`INTERNET_NAME`]
+
+If we were to look at `This is some web content: foo` in our rule, here are the `data` and `type` fields you would expect to exist (`module` would also exist but has been left out of this example for brevity):
+* `data`: `This is some web content: foo`
+* `type`: `TARGET_WEB_CONTENT`
+* `source.data`: `https://bar/page.html`
+* `source.type`: `LINKED_URL_INTERNAL`
+* `child.data`: `foo`
+* `child.type`: `INTERNET_NAME`
+* `entity.type`: `INTERNET_NAME`
+* `entity.data`: `bar`
+
+Notice how the `entity.type` and `entity.data` fields for "This is some web content: foo" is **not** the `LINKED_URL_INTERNAL` data element, but actually the `bar` `INTERNET_NAME` data element. This is because an `INTERNET_NAME` is an entity, but a `LINKED_URL_INTERNAL` is not.
+
+You can look in `spiderfoot/db.py` to see which data types are entities and which are not.
diff --git a/spiderfoot/correlations/cert_expired.yaml b/spiderfoot/correlations/cert_expired.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ff38f68f3b1d576e3bab115c4c12cce6c79da17a
--- /dev/null
+++ b/spiderfoot/correlations/cert_expired.yaml
@@ -0,0 +1,18 @@
+id: cert_expired
+version: 1
+meta:
+ name: Expired SSL certificate found
+ description: >
+ A host was found with an expired SSL certificate. This may
+ pose a risk to the security of the service exposed and/or
+ cause connecting services to fail due to being unable to
+ verify the certificate.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: SSL_CERTIFICATE_EXPIRED
+aggregation:
+ field: source.data
+headline: "Expired SSL certificate found: {source.data}"
diff --git a/spiderfoot/correlations/cloud_bucket_open.yaml b/spiderfoot/correlations/cloud_bucket_open.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..48c1110cb6edcbd3dffa33187e1e6f0d6d11fa92
--- /dev/null
+++ b/spiderfoot/correlations/cloud_bucket_open.yaml
@@ -0,0 +1,24 @@
+id: cloud_bucket_open
+version: 1
+meta:
+ name: Cloud storage bucket open to the Internet
+ description: >
+ A cloud storage bucket (e.g. S3) referenced from the target
+ website has been found to be open to the Internet. Such
+ buckets should be restricted so that contents cannot be
+ listed, even if needing to be publicly accessible.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: CLOUD_STORAGE_BUCKET
+ - method: exact
+ field: source.type
+ value: LINKED_URL_EXTERNAL
+ - method: exact
+ field: child.type
+ value: CLOUD_STORAGE_BUCKET_OPEN
+aggregation:
+ field: data
+headline: "Cloud storage bucket found open: {data}"
diff --git a/spiderfoot/correlations/cloud_bucket_open_related.yaml b/spiderfoot/correlations/cloud_bucket_open_related.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f50d20a9c39dbcf7cb5562197b55c53821f63770
--- /dev/null
+++ b/spiderfoot/correlations/cloud_bucket_open_related.yaml
@@ -0,0 +1,25 @@
+id: cloud_bucket_open_related
+version: 1
+meta:
+ name: Possibly related cloud storage bucket open to the Internet
+ description: >
+ A cloud storage bucket (e.g. S3) potentially related to
+ the target has been found to be open to the Internet.
+
+ As the buckets in this case are based on name-matching, verification
+ for actual association with the target is necessary.
+ risk: LOW
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: CLOUD_STORAGE_BUCKET
+ - method: exact
+ field: source.type
+ value: not LINKED_URL_EXTERNAL
+ - method: exact
+ field: child.type
+ value: CLOUD_STORAGE_BUCKET_OPEN
+aggregation:
+ field: data
+headline: "Potentially relevant cloud storage bucket found open: {data}"
diff --git a/spiderfoot/correlations/data_from_base64.yaml b/spiderfoot/correlations/data_from_base64.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d44fc0b6e5ece9ec5960222a6d17e7b9c161ab
--- /dev/null
+++ b/spiderfoot/correlations/data_from_base64.yaml
@@ -0,0 +1,22 @@
+id: data_from_base64
+version: 1
+meta:
+ name: Data was found within base64-encoded data
+ description: >
+ Possibly interesting data was found within base64-encoded data,
+ such as software versions, names, email addresses and hostnames.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: BASE64_DATA
+ - method: regex
+ field: child.data
+ value: .*
+ - method: exact
+ field: child.type
+ value: not HASH
+aggregation:
+ field: child.data
+headline: "Interesting data was found within base64-encoded data: '{child.data}'"
diff --git a/spiderfoot/correlations/data_from_docmeta.yaml b/spiderfoot/correlations/data_from_docmeta.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..11e5e279215de9f5409f3a5a9e5fbaf6203b4f9f
--- /dev/null
+++ b/spiderfoot/correlations/data_from_docmeta.yaml
@@ -0,0 +1,22 @@
+id: data_from_docmeta
+version: 1
+meta:
+ name: Data was found within document/image meta data
+ description: >
+ Possibly interesting data was found within document/image meta data,
+ such as software versions, names, email addresses and hostnames.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: RAW_FILE_META_DATA
+ - method: regex
+ field: child.data
+ value: .*
+ - method: exact
+ field: child.type
+ value: not HASH
+aggregation:
+ field: child.data
+headline: "Interesting data was found within document meta data: '{child.data}'"
diff --git a/spiderfoot/correlations/database_exposed.yaml b/spiderfoot/correlations/database_exposed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0e79870184c6a8a95c3c1b9dcf77b43905b709f1
--- /dev/null
+++ b/spiderfoot/correlations/database_exposed.yaml
@@ -0,0 +1,46 @@
+id: database_exposed
+version: 1
+meta:
+ name: Database server exposed to the Internet
+ description: >
+ A database technology (MySQL, Oracle, Postgres, Redis,
+ Hadoop, MongoDB, Spark) was found to be accessible over
+ the Internet.
+
+ Even if authentication is required such systems should not
+ be exposed over the Internet due to the risk of misconfiguration
+ or unpatched vulnerabilities.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: TCP_PORT_OPEN
+ - method: regex
+ field: data
+ value:
+ # MySQL
+ - .*:3306$
+ # Oracle
+ - .*:1521$
+ # PostgreSQL
+ - .*:5432$
+ # Redis
+ - .*:6379$
+ - .*:6380$
+ # Hadoop
+ - .*:50070$
+ - .*:50470$
+ - .*:50090$
+ - .*:500[12]0$
+ - .*:50475$
+ - .*:50075$
+ - .*:8020$
+ - .*:9000$
+ # Spark
+ - .*:7077$
+ # MongoDB
+ - .*:2701[789]$
+aggregation:
+ field: data
+headline: "Database server exposed to the Internet: {data}"
diff --git a/spiderfoot/correlations/dev_or_test_system.yaml b/spiderfoot/correlations/dev_or_test_system.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..de2b1b71fc5c29286e2c1437f8e82f81205f1dee
--- /dev/null
+++ b/spiderfoot/correlations/dev_or_test_system.yaml
@@ -0,0 +1,26 @@
+id: dev_or_test_system
+version: 1
+meta:
+ name: A host appearing to be a test or development system was found
+ description: >
+ A host that has dev, test, staging, internal or uat in its
+ name was found. This may indicate a system that is exposed
+ over the Internet unintentionally, and/or may be less secure
+ than other systems.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: regex
+ field: data
+ value:
+ - .*dev.*
+ - .*test.*
+ - .*uat.*
+ - .*internal.*
+ - .*staging.*
+aggregation:
+ field: data
+headline: "Development or internal system found: {data}"
diff --git a/spiderfoot/correlations/dns_zone_transfer_possible.yaml b/spiderfoot/correlations/dns_zone_transfer_possible.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7fd464494d0f4f6b335e67033461573a7b2ef4d0
--- /dev/null
+++ b/spiderfoot/correlations/dns_zone_transfer_possible.yaml
@@ -0,0 +1,18 @@
+id: dns_zone_transfer_possible
+version: 1
+meta:
+ name: DNS Zone Transfer is possible
+ description: >
+ It was possible to perform a DNS Zone Transfer with the
+ target's name server. Zone transfers can expose a significant
+ amount of information about the target network and have no
+ real need to be enabled in modern networks.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: module
+ value: sfp_dnszonexfer
+aggregation:
+ field: source.data
+headline: "DNS Zone Transfer possible with {source.data}"
diff --git a/spiderfoot/correlations/egress_ip_from_wikipedia.yaml b/spiderfoot/correlations/egress_ip_from_wikipedia.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5c257b56d371901b298e343690d2e2c24a0f4593
--- /dev/null
+++ b/spiderfoot/correlations/egress_ip_from_wikipedia.yaml
@@ -0,0 +1,33 @@
+id: egress_ip_from_wikipedia
+version: 1
+meta:
+ name: Wikipedia page edit from target-owned network
+ description: >
+ A Wikipedia page edit was found to come from an IP address
+ within a network owned by the target. That IP address is
+ highly likely to be that of a VPN server or office egress
+ proxy/gateway.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: NETBLOCK_OWNER
+ - collect:
+ - method: exact
+ field: type
+ value: IP_ADDRESS
+ - method: exact
+ field: child.type
+ value: WIKIPEDIA_PAGE_EDIT
+aggregation:
+ field: data
+analysis:
+ - method: match_all_to_first_collection
+ field: data
+ # Could also be 'contains' or 'exact'
+ match_method: subnet
+headline:
+ text: "Wikipedia edit from IP within target-owned network: {data}"
+ publish_collections:
+ - 1
diff --git a/spiderfoot/correlations/email_in_multiple_breaches.yaml b/spiderfoot/correlations/email_in_multiple_breaches.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1ed16ef95110f406d1e09775427d58fb5fad3a1d
--- /dev/null
+++ b/spiderfoot/correlations/email_in_multiple_breaches.yaml
@@ -0,0 +1,25 @@
+id: email_in_multiple_breaches
+version: 1
+meta:
+ name: >
+ An email address was reported to be in multiple breaches
+ description: >
+ An email address was reported to be in multiple breaches.
+
+ The presence in multiple breaches may indicate that the password
+ of the account is particularly weak, or that it was re-used across
+ the sites involved in the breaches. Note that some breaches simply
+ aggregate other breaches, or may be very old.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: EMAILADDR_COMPROMISED
+aggregation:
+ field: source.data
+analysis:
+ - method: threshold
+ field: source.data
+ minimum: 2
+headline: "Email address reported in multiple breaches: {source.data}"
diff --git a/spiderfoot/correlations/email_in_whois.yaml b/spiderfoot/correlations/email_in_whois.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1de7d04c11278f0f2f8be17617b076446f007ab4
--- /dev/null
+++ b/spiderfoot/correlations/email_in_whois.yaml
@@ -0,0 +1,24 @@
+id: email_in_whois
+version: 1
+meta:
+ name: A target-relevant email address was found in Whois data
+ description: >
+ An email address was found in Whois data that is directly
+ related to the target (e.g. same domain). The email found may
+ be that of a highly privileged person responsible for
+ maintaining the infrastructure of the target.
+
+ Email addresses are increasingly rarely found in Whois data due
+ to GDPR.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: EMAILADDR
+ - method: regex
+ field: source.type
+ value: .*WHOIS.*
+aggregation:
+ field: data
+headline: "Email address found in Whois record: {data}"
diff --git a/spiderfoot/correlations/email_only_from_pasteleak_site.yaml b/spiderfoot/correlations/email_only_from_pasteleak_site.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..56e0c90a08b561b13fbb7b2cdac49e688df95cbb
--- /dev/null
+++ b/spiderfoot/correlations/email_only_from_pasteleak_site.yaml
@@ -0,0 +1,35 @@
+id: email_only_from_pasteleak_site
+version: 1
+meta:
+ name: Email address only from paste/leak site
+ description: >
+ An email address was found mentioned in a paste/leak site but
+ nowhere else.
+
+ Since the email address was not found anywhere else, this may indicate
+ that the address is in some way special, perhaps not intended to
+ be publicly exposed/used or targeted in an attack.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: EMAILADDR
+ - method: exact
+ field: source.type
+ value:
+ - LEAKSITE_CONTENT
+ - collect:
+ - method: exact
+ field: type
+ value: EMAILADDR
+ - method: exact
+ field: source.type
+ value:
+ - not LEAKSITE_CONTENT
+aggregation:
+ field: data
+analysis:
+ - method: first_collection_only
+ field: data
+headline: "Email address found only in paste/leak site: {data}"
diff --git a/spiderfoot/correlations/host_only_from_bruteforce.yaml b/spiderfoot/correlations/host_only_from_bruteforce.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..58206fb5988c1f6f3689ffc33fe4a2668ff68414
--- /dev/null
+++ b/spiderfoot/correlations/host_only_from_bruteforce.yaml
@@ -0,0 +1,32 @@
+id: host_only_from_bruteforce
+version: 1
+meta:
+ name: Host only from bruteforcing
+ description: >
+ A hostname was found only by brute-forcing but nowhere else.
+
+ Since the host was not found anywhere else, this may indicate
+ that the host is in some way special, perhaps not intended to
+ be publicly exposed/used.
+ risk: LOW
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: module
+ value: sfp_dnsbrute
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: module
+ value: not sfp_dnsbrute
+aggregation:
+ field: data
+analysis:
+ - method: first_collection_only
+ field: data
+headline: "Host found only through bruteforcing: {data}"
diff --git a/spiderfoot/correlations/host_only_from_certificatetransparency.yaml b/spiderfoot/correlations/host_only_from_certificatetransparency.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..71f0bf0ca67ca661ae91f26a0f4d9135591a9b1c
--- /dev/null
+++ b/spiderfoot/correlations/host_only_from_certificatetransparency.yaml
@@ -0,0 +1,38 @@
+id: host_only_from_certificatetransparency
+version: 1
+meta:
+ name: Hostname only from certificate transparency
+ description: >
+ A hostname was found from certificate transparency but
+ nowhere else.
+
+ Since the host was not found anywhere else, this may indicate
+ that the host is in some way special, perhaps not intended to
+ be publicly exposed/used.
+ risk: LOW
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: module
+ value:
+ - sfp_crt
+ - sfp_certspotter
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: module
+ value:
+ - not sfp_crt
+ - not sfp_certspotter
+ - not sfp_dnsresolve
+aggregation:
+ field: data
+analysis:
+ - method: first_collection_only
+ field: data
+headline: "Host found only in certificate transparency: {data}"
diff --git a/spiderfoot/correlations/http_errors.yaml b/spiderfoot/correlations/http_errors.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a036067fb57b97837a077addd5432cdcf2897191
--- /dev/null
+++ b/spiderfoot/correlations/http_errors.yaml
@@ -0,0 +1,28 @@
+id: http_errors
+version: 1
+meta:
+ name: Multiple HTTP errors found
+ description: >
+ Non-successful HTTP error codes were encountered. 401 and 403
+ are not included as these refer to authentication/authorization
+ failures.
+ risk: LOW
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: HTTP_CODE
+ - method: regex
+ field: data
+ value: ^[4-9].*$
+ # Leave out authentication/authorization failures
+ - method: regex
+ field: data
+ value: not 40[13]
+aggregation:
+ field: entity.data
+analysis:
+ - method: threshold
+ minimum: 2
+ field: data
+headline: "Multiple failure HTTP codes found at {entity.data}"
diff --git a/spiderfoot/correlations/human_name_in_whois.yaml b/spiderfoot/correlations/human_name_in_whois.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..89ee72ec160d284fbeaf48def82ecbba733b866c
--- /dev/null
+++ b/spiderfoot/correlations/human_name_in_whois.yaml
@@ -0,0 +1,23 @@
+id: human_name_in_whois
+version: 1
+meta:
+ name: A human name was found in Whois data
+ description: >
+ A human name was found in Whois data. The name found may
+ be that of a highly privileged person responsible for
+ maintaining the infrastructure of the target.
+
+ Names are increasingly rarely found in Whois data due to
+ GDPR.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: HUMAN_NAME
+ - method: regex
+ field: source.type
+ value: .*WHOIS.*
+aggregation:
+ field: data
+headline: "Human name found in Whois record: {data}"
diff --git a/spiderfoot/correlations/internal_host.yaml b/spiderfoot/correlations/internal_host.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..78fb4677171339af2a25d50fac83588e45ab3fb4
--- /dev/null
+++ b/spiderfoot/correlations/internal_host.yaml
@@ -0,0 +1,30 @@
+id: internal_host
+version: 1
+meta:
+ name: A host resolving to unroutable IPs was found
+ description: >
+ A host that resolves to an IP address on ranges reserved for
+ internal use (10.0.0.0/8, etc.) was found to be publicly
+ resolvable. This might reveal information about the internal
+ infrastructure and workings of the target.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNAL_IP_ADDRESS
+ - collect:
+ - method: exact
+ field: type
+ value: IP_ADDRESS
+ - method: regex
+ field: data
+ value:
+ - ^192\\.168\\..*
+ - ^10\\..*
+ - method: exact
+ field: module
+ value: sfp_dnsresolve
+aggregation:
+ field: data
+headline: "An internal host was found: {data}"
diff --git a/spiderfoot/correlations/multiple_malicious.yaml b/spiderfoot/correlations/multiple_malicious.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d6174fe6351bfea8ab43637590ea793e76e86c13
--- /dev/null
+++ b/spiderfoot/correlations/multiple_malicious.yaml
@@ -0,0 +1,39 @@
+id: multiple_malicious
+version: 1
+meta:
+ name: >
+ An IP, host, subnet or email address was considered malicious by
+ multiple sources
+ description: >
+ An IP, host, subnet or email address was considered malicious by
+ multiple sources.
+
+ Such cases have a high likelihood of being genuinely malicious and
+ should be urgently investigated. Even if the entity in question is
+ not compromised, it's likely to be blocked across parts of the
+ Internet due to its presence in these lists.
+ risk: HIGH
+collections:
+ - collect:
+ - method: regex
+ field: type
+ value:
+ - MALICIOUS_*
+ - BLACKLIST_*
+ # Filter out all subnets
+ - method: regex
+ field: source.data
+ value: not .*/.*
+ # Filter out affiliates and Co-hosts
+ - method: regex
+ field: type
+ value:
+ - not .*COHOST.*
+ - not .*AFFILIATE.*
+aggregation:
+ field: source.data
+analysis:
+ - method: threshold
+ field: source.data
+ minimum: 2
+headline: "Entity considered malicious by multiple sources: {source.data}"
diff --git a/spiderfoot/correlations/multiple_malicious_affiliate.yaml b/spiderfoot/correlations/multiple_malicious_affiliate.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..27290c659965dcf21b9397fbed7c8acc6c55bf53
--- /dev/null
+++ b/spiderfoot/correlations/multiple_malicious_affiliate.yaml
@@ -0,0 +1,33 @@
+id: multiple_malicious_affiliate
+version: 1
+meta:
+ name: >
+ An affiliated IP or host was considered malicious by multiple sources
+ description: >
+ An affiliated IP or host was considered malicious by multiple sources.
+
+ Such cases have a high likelihood of being genuinely malicious and
+ should be investigated depending on the nature of the relationship
+ between the target and the affiliate. Even if the entity in question is
+ not compromised, it's likely to be blocked across parts of the
+ Internet due to its presence in these lists and may therefore have
+ an impact on the target.
+ risk: LOW
+collections:
+ - collect:
+ - method: regex
+ field: type
+ value:
+ - MALICIOUS_*
+ - BLACKLIST_*
+ # Filter to only affiliated entities
+ - method: regex
+ field: type
+ value: .*AFFILIATE.*
+aggregation:
+ field: source.data
+analysis:
+ - method: threshold
+ field: source.data
+ minimum: 2
+headline: "Affiliated entity considered malicious by multiple sources: {source.data}"
diff --git a/spiderfoot/correlations/multiple_malicious_cohost.yaml b/spiderfoot/correlations/multiple_malicious_cohost.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..599ba23e882b3387cbe9aa71f4ccc52dd25042da
--- /dev/null
+++ b/spiderfoot/correlations/multiple_malicious_cohost.yaml
@@ -0,0 +1,33 @@
+id: multiple_malicious_cohost
+version: 1
+meta:
+ name: >
+ A co-hosted site was considered malicious by multiple sources
+ description: >
+ A co-hosted site was considered malicious by multiple sources.
+
+ Such cases have a high likelihood of being genuinely malicious and
+ should be investigated depending on the nature of the relationship
+ between the target and the co-host. Even if the entity in question is
+ not compromised, it's likely to be blocked across parts of the
+ Internet due to its presence in these lists and may therefore have
+ an impact on the target.
+ risk: LOW
+collections:
+ - collect:
+ - method: regex
+ field: type
+ value:
+ - MALICIOUS_*
+ - BLACKLIST_*
+ # Filter to only co-hosted sites
+ - method: regex
+ field: type
+ value: .*COHOST.*
+aggregation:
+ field: source.data
+analysis:
+ - method: threshold
+ field: source.data
+ minimum: 2
+headline: "Co-hosted site considered malicious by multiple sources: {source.data}"
diff --git a/spiderfoot/correlations/name_only_from_pasteleak_site.yaml b/spiderfoot/correlations/name_only_from_pasteleak_site.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..49b7093ce91b3154b094506ee533d2f99553cd06
--- /dev/null
+++ b/spiderfoot/correlations/name_only_from_pasteleak_site.yaml
@@ -0,0 +1,35 @@
+id: name_only_from_pasteleak_site
+version: 1
+meta:
+ name: Human name only from paste/leak site
+ description: >
+ A human name was found mentioned in a paste/leak site but
+ nowhere else.
+
+ Since the name was not found anywhere else, this may indicate
+ that the name is in some way special, perhaps not intended to
+ be publicly exposed/used or targeted in an attack.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: source.type
+ value:
+ - LEAKSITE_CONTENT
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ - method: exact
+ field: source.type
+ value:
+ - not LEAKSITE_CONTENT
+aggregation:
+ field: data
+analysis:
+ - method: first_collection_only
+ field: data
+headline: "Human name found only in paste/leak site: {data}"
diff --git a/spiderfoot/correlations/open_port_version.yaml b/spiderfoot/correlations/open_port_version.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f85019ea0ce60135d9e765b51f4e4eaefe4bb487
--- /dev/null
+++ b/spiderfoot/correlations/open_port_version.yaml
@@ -0,0 +1,26 @@
+id: open_port_version
+version: 1
+meta:
+ name: Open TCP port reveals version
+ description: >
+ A possible software version has been revealed on an open port. Such
+ information may reveal the use of old/unpatched software used by
+ the target.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: TCP_PORT_OPEN_BANNER
+ - method: regex
+ field: data
+ value: .*[0-9]\.[0-9].*
+ - method: regex
+ field: data
+ value: not .*Mime-Version.*
+ - method: regex
+ field: data
+ value: not .*HTTP/1.*
+aggregation:
+ field: data
+headline: "Software version revealed on open port: {data}"
diff --git a/spiderfoot/correlations/outlier_cloud.yaml b/spiderfoot/correlations/outlier_cloud.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d738897e2d3a3fff7c26cc1d0e042353b1d6f738
--- /dev/null
+++ b/spiderfoot/correlations/outlier_cloud.yaml
@@ -0,0 +1,24 @@
+id: outlier_cloud
+version: 1
+meta:
+ name: Outlier Cloud provider
+ description: >
+ A cloud provider that appeared in 10% or less of the
+ total providers found. Outliers can often reveal
+ entities that are rare and therefore interesting.
+
+ Particularly in the case of cloud providers, an outlier
+ may be an indicator of Shadow IT or unmtaintained
+ infrastructure.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: PROVIDER_HOSTING
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier cloud provider found: {data}"
diff --git a/spiderfoot/correlations/outlier_country.yaml b/spiderfoot/correlations/outlier_country.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c6bf8a225053c0657f730c50ab35b0cf84cdf543
--- /dev/null
+++ b/spiderfoot/correlations/outlier_country.yaml
@@ -0,0 +1,20 @@
+id: outlier_country
+version: 1
+meta:
+ name: Outlier country
+ description: >
+ A country that appeared in 10% or less of the total countries
+ found. Outliers can often reveal entities that are rare and
+ therefore interesting.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: COUNTRY_NAME
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier country found: {data}"
diff --git a/spiderfoot/correlations/outlier_email.yaml b/spiderfoot/correlations/outlier_email.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..125b0dfce66319911e9780d839e896ed9141d40b
--- /dev/null
+++ b/spiderfoot/correlations/outlier_email.yaml
@@ -0,0 +1,20 @@
+id: outlier_email
+version: 1
+meta:
+ name: Outlier email address found
+ description: >
+ An email address that appeared in 10% or less of the
+ total email addresses found. Outliers can often reveal
+ entities that are rare and therefore interesting.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: EMAILADDR
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier email address found: {data}"
diff --git a/spiderfoot/correlations/outlier_hostname.yaml b/spiderfoot/correlations/outlier_hostname.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..8e0e6bf32a52afd4946b0686f51bcd2238dc2506
--- /dev/null
+++ b/spiderfoot/correlations/outlier_hostname.yaml
@@ -0,0 +1,20 @@
+id: outlier_hostname
+version: 1
+meta:
+ name: Outlier hostname
+ description: >
+ A hostname that appeared in 10% or less of the
+ total hostnames found. Outliers can often reveal
+ entities that are rare and therefore interesting.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier hostname found: {data}"
diff --git a/spiderfoot/correlations/outlier_ipaddress.yaml b/spiderfoot/correlations/outlier_ipaddress.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c45c90637fc7a55590e5dade49a3be74b09b9dbe
--- /dev/null
+++ b/spiderfoot/correlations/outlier_ipaddress.yaml
@@ -0,0 +1,22 @@
+id: outlier_ipaddress
+version: 1
+meta:
+ name: Outlier IP address
+ description: >
+ An IP address that appeared in 10% or less of the
+ total IP addresses found. Outliers can often reveal
+ entities that are rare and therefore interesting.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value:
+ - IP_ADDRESS
+ - IPV6_ADDRESS
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier IP address found: {data}"
diff --git a/spiderfoot/correlations/outlier_registrar.yaml b/spiderfoot/correlations/outlier_registrar.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..156eeb5dc42512a1d58ded6ad7bd72e9ccbaaec2
--- /dev/null
+++ b/spiderfoot/correlations/outlier_registrar.yaml
@@ -0,0 +1,23 @@
+id: outlier_registrar
+version: 1
+meta:
+ name: Outlier registrar
+ description: >
+ A registrar that appeared in 10% or less of the total registrars
+ found. Outliers can often reveal entities that are rare and
+ therefore interesting.
+
+ Particularly in the case of registrars, an outlier may be an
+ indicator of Shadow IT or unmtaintained infrastructure.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: DOMAIN_REGISTRAR
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier registrar found: {data}"
diff --git a/spiderfoot/correlations/outlier_webserver.yaml b/spiderfoot/correlations/outlier_webserver.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5d66bdc1962f5f0f10b6c8cb886f25311a93f828
--- /dev/null
+++ b/spiderfoot/correlations/outlier_webserver.yaml
@@ -0,0 +1,24 @@
+id: outlier_webserver
+version: 1
+meta:
+ name: Outlier web server
+ description: >
+ A web server that appeared in 10% or less of the
+ total web servers found. Outliers can often reveal
+ entities that are rare and therefore interesting.
+
+ Particularly in the case of web servers, an outlier
+ may be an indicator of Shadow IT or unmtaintained
+ infrastructure.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: WEBSERVER_BANNER
+aggregation:
+ field: data
+analysis:
+ - method: outlier
+ maximum_percent: 10
+headline: "Outlier web server found: {data}"
diff --git a/spiderfoot/correlations/remote_desktop_exposed.yaml b/spiderfoot/correlations/remote_desktop_exposed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..405c17c34576e9b97601d814c089a733315e4f17
--- /dev/null
+++ b/spiderfoot/correlations/remote_desktop_exposed.yaml
@@ -0,0 +1,26 @@
+id: remote_desktop_exposed
+version: 1
+meta:
+ name: Remote desktop technology found exposed to the Internet
+ description: >
+ A remote desktop technology (RDP, VNC, NoMachine)
+ was found to be accessible over the Internet.
+
+ Even if authentication is required such systems should not
+ be exposed over the Internet due to the risk of misconfiguration
+ or unpatched vulnerabilities.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: TCP_PORT_OPEN
+ - method: regex
+ field: data
+ value:
+ - .*:5900$
+ - .*:3389$
+ - .*:4000$
+aggregation:
+ field: source.data
+headline: "Remote desktop exposed to the Internet: {source.data}"
diff --git a/spiderfoot/correlations/root_path_needs_auth.yaml b/spiderfoot/correlations/root_path_needs_auth.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..654378f5a03fce1f85574f2593c0d3b9cfb3e1ac
--- /dev/null
+++ b/spiderfoot/correlations/root_path_needs_auth.yaml
@@ -0,0 +1,25 @@
+id: root_path_needs_auth
+version: 1
+meta:
+ name: Website root path needs authentication
+ description: >
+ The base path of a server needs authentication, indicating the
+ server is likely sensitive or important.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: HTTP_CODE
+ - method: regex
+ field: data
+ value: 40[31]
+ # The source might be a host or URL
+ - method: regex
+ field: source.data
+ value:
+ - ^https?://[a-zA-Z0-9\.\-]+/?#?$
+ - ^[a-zA-Z0-9\.\-]+$
+aggregation:
+ field: source.data
+headline: "Base URL requires authentication: {source.data}"
diff --git a/spiderfoot/correlations/stale_host.yaml b/spiderfoot/correlations/stale_host.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..437d64c3760fa1ee5d22dd4eab2e60fd2b111c44
--- /dev/null
+++ b/spiderfoot/correlations/stale_host.yaml
@@ -0,0 +1,48 @@
+id: stale_host
+version: 1
+meta:
+ name: Stale host found
+ description: >
+ A host appears to be stale based upon various indicators such
+ as unsuccessful HTTP codes, expired SSL certificates, error
+ messages, vulnerabilities and junk files found. Such hosts
+ may be unmaintained, exposing the target to security risks.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: SSL_CERTIFICATE_EXPIRED
+ - collect:
+ - method: exact
+ field: type
+ value: HTTP_CODE
+ - method: regex
+ field: data
+ value: not ^[2-3].*$
+ - method: regex
+ field: data
+ value: not 40[13]
+ - collect:
+ - method: exact
+ field: type
+ value: ERROR_MESSAGE
+ - collect:
+ - method: exact
+ field: type
+ value: JUNK_FILE
+ - collect:
+ - method: regex
+ field: type
+ value: VULNERABILITY_.*
+aggregation:
+ field: entity.data
+analysis:
+ - method: threshold
+ field: type
+ # Avoid multiple of the same type triggering. This means
+ # a minimum of 3 of different types must appear in one
+ # bucket.
+ count_unique_only: true
+ minimum: 3
+headline: "Potentially stale/unmaintained host: {entity.data}"
diff --git a/spiderfoot/correlations/strong_affiliate_certs.yaml b/spiderfoot/correlations/strong_affiliate_certs.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c4b1ae072ad6e07731c4dc793dd43348b90b5759
--- /dev/null
+++ b/spiderfoot/correlations/strong_affiliate_certs.yaml
@@ -0,0 +1,39 @@
+id: strong_affiliate_certs
+version: 1
+meta:
+ name: Affiliated host/domain with strong relationship to the target
+ description: >
+ A host or domain was found to be referenced multiple times from
+ SSL certificates covering multiple target hosts.
+
+ Strong affiliates indicate potential targets that should be
+ included in the scope of scanning to ensure more complete coverage.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: module
+ value:
+ - sfp_sslcert
+ - sfp_crt
+ - sfp_certspotter
+ - method: exact
+ field: source.type
+ value:
+ - INTERNET_NAME
+ - DOMAIN_NAME
+ - method: exact
+ field: type
+ value:
+ - AFFILIATE_INTERNET_NAME
+ - AFFILIATE_DOMAIN_NAME
+ - CO_HOSTED_SITE
+ - CO_HOSTED_SITE_DOMAIN
+aggregation:
+ field: data
+analysis:
+ - method: threshold
+ field: source.data
+ count_unique_only: true
+ minimum: 2
+headline: "Affiliate with strong target relationship: {data}"
diff --git a/spiderfoot/correlations/strong_similardomain_crossref.yaml b/spiderfoot/correlations/strong_similardomain_crossref.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c6d27367fe8dc4fbbb208fddb3b6dc192e55c339
--- /dev/null
+++ b/spiderfoot/correlations/strong_similardomain_crossref.yaml
@@ -0,0 +1,25 @@
+id: strong_similardomain_crossref
+version: 1
+meta:
+ name: Similar domain with strong relationship to the target
+ description: >
+ A similar domain was found to be referenced by the target, and
+ references back, indicating a strong relationship.
+
+ Strong affiliates indicate potential targets that should be
+ included in the scope of scanning to ensure more complete coverage.
+ risk: INFO
+collections:
+ - collect:
+ - method: exact
+ field: module
+ value: sfp_crossref
+ - method: exact
+ field: type
+ value: AFFILIATE_INTERNET_NAME
+ - method: exact
+ field: source.type
+ value: SIMILARDOMAIN
+aggregation:
+ field: data
+headline: "Similar domain with strong target relationship: {data}"
diff --git a/spiderfoot/correlations/template.yaml b/spiderfoot/correlations/template.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2c4267981da962dc63b252d2b5225b8f9a6c9321
--- /dev/null
+++ b/spiderfoot/correlations/template.yaml
@@ -0,0 +1,89 @@
+# Set the ID for the rule. Ensure it matches the filename (without the .yaml
+# extension) and has no spaces or other special characters.
+id: set_a_meaningful_id_here
+
+# Use version 1 for now.
+version: 1
+
+# The meta section sets meta attributes about the rule.
+meta:
+
+ # The human-readable name for the rule
+ name: This is a briefly descriptive name.
+
+ # A longer description for the rule
+ description: >
+ This is a more detailed description about the rule and ideally
+ includes some rationale explaining the risk posed, or other
+ relevant information that helps the user better understand the
+ value of the rule results.
+
+ You can have multiple paragraphs here too.
+
+ For this example rule, our goal is to find all hosts that
+ match "foo" or "bar", creating a correlation result when such a
+ host is found more than once.
+
+ # The risk the results of this rule posed. They can be one of:
+ # - HIGH (reserved for genuine cases requiring immediate action)
+ # - MEDIUM (potential high risk, needs deeper examination)
+ # - LOW (potential risk, but probably low risk or false positive)
+ # - INFO (no risk posed but potential interesting information)
+ risk: MEDIUM
+
+# Define the collections to perform here. Refer to the README.md
+# in the correlations folder for more details.
+collections:
+
+ # Each 'collect' block represents a collection of data from
+ # the SpiderFoot database. You need at least one 'collect'
+ # block for the rule to actually do something.
+ - collect:
+ # Each 'collect' block may contain multiple blocks
+ # for collecting and analyzing data. The first pulls
+ # data from the SpiderFoot database, and subsequent
+ # blocks further refine that data down to what you are
+ # interested in. You need at least one for the 'collect'
+ # block to have data.
+ #
+ # For example, this rule will extract all data elements
+ # that exactly match the INTERNET_NAME type.
+ - method: exact
+ field: type
+ value: INTERNET_NAME
+ # This next rule will filter out all the INTERNET_NAME
+ # results where data doesn't match any of the regular
+ # expressions provided.
+ - method: regex
+ field: data
+ value:
+ - .*foo.*
+ - .*bar.*
+ # What we are now left with in this collection are all
+ # INTERNET_NAME elements with data matching either .*foo.*
+ # or .*bar.*
+
+# With the data from your one or more collections, you can
+# now use 'aggregation' to define how they should be grouped
+# (if at all) for analysis at the next stage (also optional).
+aggregation:
+ # Each data element will be placed into a bucket according
+ # to its data field, which is the hostname since we have
+ # INTERNET_NAME data elements.
+ field: data
+
+# Analysis is an optional step to perform analysis on the
+# (optionally aggegated) data gathered to apply some criteria
+# determining whether a correlation creates results or not.
+analysis:
+ # Here we want to only generate a correlation result when
+ # the value of the data element's data field (the hostname
+ # in this case) appears at least two times.
+ - method: threshold
+ minimum: 2
+ field: data
+
+# With the collection, aggegation and analysis performed,
+# we can now generate the correlation result with a title
+# that represents something meaningful to the user.
+headline: "A foo or bar host was found more than once: {data}"
diff --git a/spiderfoot/correlations/vulnerability_critical.yaml b/spiderfoot/correlations/vulnerability_critical.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..58d98c8ea4ef213f8c069669560f98dc2c1b3166
--- /dev/null
+++ b/spiderfoot/correlations/vulnerability_critical.yaml
@@ -0,0 +1,18 @@
+id: vulnerability_critical
+version: 1
+meta:
+ name: At least one CRITICAL-rated vulnerability was found
+ description: >
+ A vulnerability rated as CRITICAL was found on a host.
+
+ Such vulnerabilities are typically easily exploitable and should
+ be urgently patched.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: VULNERABILITY_CVE_CRITICAL
+aggregation:
+ field: entity.data
+headline: "Critical-rated vulnerability found on {entity.data}"
diff --git a/spiderfoot/correlations/vulnerability_high.yaml b/spiderfoot/correlations/vulnerability_high.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..95a94349055675d05493b2e4222b763d1a260082
--- /dev/null
+++ b/spiderfoot/correlations/vulnerability_high.yaml
@@ -0,0 +1,18 @@
+id: vulnerability_high
+version: 1
+meta:
+ name: At least one HIGH-rated vulnerability was found
+ description: >
+ A vulnerability rated as HIGH was found on a host.
+
+ Such vulnerabilities are typically easily exploitable and should
+ be urgently patched.
+ risk: HIGH
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value: VULNERABILITY_CVE_HIGH
+aggregation:
+ field: entity.data
+headline: "High-rated vulnerability found on {entity.data}"
diff --git a/spiderfoot/correlations/vulnerability_mediumlow.yaml b/spiderfoot/correlations/vulnerability_mediumlow.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dd3527f41978ce41892118589c187b1b78a84b15
--- /dev/null
+++ b/spiderfoot/correlations/vulnerability_mediumlow.yaml
@@ -0,0 +1,25 @@
+id: vulnerability_mediumlow
+version: 1
+meta:
+ name: Multiple MEDIUM or LOW-rated vulnerabilities were found
+ description: >
+ Multiple vulnerabilities rated as MEDIUM or LOW were found on a host.
+
+ Such vulnerabilities pose a lower risk to the target, however in
+ aggregate may be an indication that the host is not well maintained.
+ risk: MEDIUM
+collections:
+ - collect:
+ - method: exact
+ field: type
+ value:
+ - VULNERABILITY_CVE_MEDIUM
+ - VULNERABILITY_CVE_LOW
+ - VULNERABILITY_GENERAL
+aggregation:
+ field: entity.data
+analysis:
+ - method: threshold
+ field: entity.data
+ minimum: 2
+headline: "Multiple medium/low vulnerabilities found on {entity.data}"
diff --git a/spiderfoot/docker-compose-dev.yml b/spiderfoot/docker-compose-dev.yml
new file mode 100644
index 0000000000000000000000000000000000000000..650a72f9a3cea3e6e044ce786dbca7ab927ab575
--- /dev/null
+++ b/spiderfoot/docker-compose-dev.yml
@@ -0,0 +1,6 @@
+version: "3"
+
+services:
+ spiderfoot:
+ volumes:
+ - .:/home/spiderfoot
diff --git a/spiderfoot/docker-compose-full.yml b/spiderfoot/docker-compose-full.yml
new file mode 100644
index 0000000000000000000000000000000000000000..eceb3f1e0588f88a54b229c501b5d7e631382e49
--- /dev/null
+++ b/spiderfoot/docker-compose-full.yml
@@ -0,0 +1,7 @@
+version: "3"
+
+services:
+ spiderfoot:
+ build:
+ context: ./
+ dockerfile: ./Dockerfile.full
diff --git a/spiderfoot/docker-compose.yml b/spiderfoot/docker-compose.yml
new file mode 100644
index 0000000000000000000000000000000000000000..bdf0e63f35664718503216af9f7982c9c6247dda
--- /dev/null
+++ b/spiderfoot/docker-compose.yml
@@ -0,0 +1,32 @@
+version: "3"
+
+# Basic usage:
+# $ docker-compose up
+#
+# Dev environment (code directory mapped into container):
+# $ docker-compose -f docker-compose.yml -f docker-compose-dev.yml up
+#
+# Full image (all CLI tools installed):
+# $ docker-compose -f docker-compose.yml -f docker-compose-full.yml up
+#
+# Spiderfoot data resides in a Docker volume
+#
+# $ ls -lh /var/lib/docker/volumes/spiderfoot_spiderfoot-data/_data
+# total 104K
+# drwxr-xr-x 2 user user 4.0K Sep 22 09:51 cache
+# -rw-r--r-- 1 user user 100K Sep 22 15:19 spiderfoot.db
+
+services:
+ spiderfoot:
+ build:
+ context: ./
+ volumes:
+ - spiderfoot-data:/var/lib/spiderfoot
+ image: spiderfoot
+ container_name: spiderfoot
+ ports:
+ - "5001:5001"
+ restart: unless-stopped
+
+volumes:
+ spiderfoot-data:
diff --git a/spiderfoot/docs/Makefile b/spiderfoot/docs/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..73a28c7134cd1760744f34bac4ebdedfbed40f72
--- /dev/null
+++ b/spiderfoot/docs/Makefile
@@ -0,0 +1,20 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS ?=
+SPHINXBUILD ?= sphinx-build
+SOURCEDIR = .
+BUILDDIR = _build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/spiderfoot/docs/conf.py b/spiderfoot/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..296bb57beb90038062a90f78c4053f14f1f4005e
--- /dev/null
+++ b/spiderfoot/docs/conf.py
@@ -0,0 +1,71 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# This file only contains a selection of the most common options. For a full
+# list see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+# import os
+# import sys
+# sys.path.insert(0, '/root/Desktop/spiderfoot/spiderfoot')
+
+
+# -- Project information -----------------------------------------------------
+
+project = 'SpiderFoot'
+copyright = '2012, Steve Micallef'
+author = 'Steve Micallef'
+
+
+# -- General configuration ---------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.napoleon',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.todo',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = 'en'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'alabaster'
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+
+# -- Extension configuration -------------------------------------------------
+
+# -- Options for todo extension ----------------------------------------------
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = True
diff --git a/spiderfoot/docs/index.rst b/spiderfoot/docs/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..c120369d06560995c070eb52b845a230084156a0
--- /dev/null
+++ b/spiderfoot/docs/index.rst
@@ -0,0 +1,21 @@
+.. spiderfoot documentation master file, created by
+ sphinx-quickstart on Sat Jun 26 01:55:34 2021.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to spiderfoot's documentation!
+======================================
+
+.. toctree::
+ :maxdepth: 4
+ :caption: Contents:
+
+ spiderfoot
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
diff --git a/spiderfoot/docs/make.bat b/spiderfoot/docs/make.bat
new file mode 100644
index 0000000000000000000000000000000000000000..2119f51099bf37e4fdb6071dce9f451ea44c62dd
--- /dev/null
+++ b/spiderfoot/docs/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=.
+set BUILDDIR=_build
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+
+:end
+popd
diff --git a/spiderfoot/docs/spiderfoot.rst b/spiderfoot/docs/spiderfoot.rst
new file mode 100644
index 0000000000000000000000000000000000000000..85ab6fd03b1ea3653db44fffbb0bb29d8384dbbf
--- /dev/null
+++ b/spiderfoot/docs/spiderfoot.rst
@@ -0,0 +1,53 @@
+spiderfoot package
+==================
+
+Submodules
+----------
+
+spiderfoot.db module
+--------------------
+
+.. automodule:: spiderfoot.db
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
+spiderfoot.event module
+-----------------------
+
+.. automodule:: spiderfoot.event
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
+spiderfoot.helpers module
+-------------------------
+
+.. automodule:: spiderfoot.helpers
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
+spiderfoot.plugin module
+------------------------
+
+.. automodule:: spiderfoot.plugin
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
+spiderfoot.target module
+------------------------
+
+.. automodule:: spiderfoot.target
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
+Module contents
+---------------
+
+.. automodule:: spiderfoot
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/spiderfoot/generate-certificate b/spiderfoot/generate-certificate
new file mode 100644
index 0000000000000000000000000000000000000000..45ff1d5c11bcd3288f8193131b1dc9a6399dc1ee
--- /dev/null
+++ b/spiderfoot/generate-certificate
@@ -0,0 +1,20 @@
+#!/bin/sh
+if ! command -v openssl >/dev/null 2>&1 ; then
+ echo "Error: Could not find openssl in \$PATH: $PATH"
+ exit 1
+fi
+
+if test -f spiderfoot.key; then
+ echo "Error: spiderfoot.key already exists"
+ exit 1
+fi
+
+if test -f spiderfoot.crt; then
+ echo "Error: spiderfoot.crt already exists"
+ exit 1
+fi
+
+openssl req -new -newkey rsa:4096 -sha256 -x509 -days 365 -nodes -out spiderfoot.crt -keyout spiderfoot.key -subj "/CN=localhost"
+
+chmod 600 spiderfoot.crt
+chmod 600 spiderfoot.key
diff --git a/spiderfoot/modules/__init__.py b/spiderfoot/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/spiderfoot/modules/sfp__stor_db.py b/spiderfoot/modules/sfp__stor_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b3126f2df1150096ac9a9e44d8bd64396916c23
--- /dev/null
+++ b/spiderfoot/modules/sfp__stor_db.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_stor_db
+# Purpose: SpiderFoot plug-in for storing events to the local SpiderFoot
+# SQLite database.
+#
+# Author: Steve Micallef
+#
+# Created: 14/05/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootPlugin
+
+
+class sfp__stor_db(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Storage",
+ 'summary': "Stores scan results into the back-end SpiderFoot database. You will need this."
+ }
+
+ _priority = 0
+
+ # Default options
+ opts = {
+ 'maxstorage': 1024, # max bytes for any piece of info stored (0 = unlimited)
+ '_store': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'maxstorage': "Maximum bytes to store for any piece of information retrieved (0 = unlimited.)"
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ # Because this is a storage plugin, we are interested in everything so we
+ # can store all events for later analysis.
+ def watchedEvents(self):
+ return ["*"]
+
+ # Handle events sent to this module
+ def handleEvent(self, sfEvent):
+ if not self.opts['_store']:
+ return
+
+ if self.opts['maxstorage'] != 0 and len(sfEvent.data) > self.opts['maxstorage']:
+ self.debug("Storing an event: " + sfEvent.eventType)
+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent, self.opts['maxstorage'])
+ return
+
+ self.debug("Storing an event: " + sfEvent.eventType)
+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent)
+
+# End of sfp__stor_db class
diff --git a/spiderfoot/modules/sfp__stor_stdout.py b/spiderfoot/modules/sfp__stor_stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..e502aaf232983195bc20bcf56180f71db1a3362c
--- /dev/null
+++ b/spiderfoot/modules/sfp__stor_stdout.py
@@ -0,0 +1,117 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_stor_stdout
+# Purpose: SpiderFoot plug-in for dumping events to standard output.
+#
+# Author: Steve Micallef
+#
+# Created: 22/10/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootPlugin
+
+
+class sfp__stor_stdout(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Command-line output",
+ 'summary': "Dumps output to standard out. Used for when a SpiderFoot scan is run via the command-line."
+ }
+
+ _priority = 0
+ firstEvent = True
+
+ # Default options
+ opts = {
+ "_format": "tab", # tab, csv, json
+ "_requested": [],
+ "_showonlyrequested": False,
+ "_stripnewline": False,
+ "_showsource": False,
+ "_csvdelim": ",",
+ "_maxlength": 0,
+ "_eventtypes": dict()
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ # Because this is a storage plugin, we are interested in everything so we
+ # can store all events for later analysis.
+ def watchedEvents(self):
+ return ["*"]
+
+ def output(self, event):
+ d = self.opts['_csvdelim']
+ if type(event.data) in [list, dict]:
+ data = str(event.data)
+ else:
+ data = event.data
+
+ if type(data) != str:
+ data = str(event.data)
+
+ if type(event.sourceEvent.data) in [list, dict]:
+ srcdata = str(event.sourceEvent.data)
+ else:
+ srcdata = event.sourceEvent.data
+
+ if type(srcdata) != str:
+ srcdata = str(event.sourceEvent.data)
+
+ if self.opts['_stripnewline']:
+ data = data.replace("\n", " ").replace("\r", "")
+ srcdata = srcdata.replace("\n", " ").replace("\r", "")
+
+ if "" in data:
+ data = data.replace("", "").replace(" ", "")
+ if "" in srcdata:
+ srcdata = srcdata.replace("", "").replace(" ", "")
+
+ if self.opts['_maxlength'] > 0:
+ data = data[0:self.opts['_maxlength']]
+ srcdata = srcdata[0:self.opts['_maxlength']]
+
+ if self.opts['_format'] == "tab":
+ event_type = self.opts['_eventtypes'][event.eventType]
+ if self.opts['_showsource']:
+ print(f"{event.module.ljust(30)}\t{event_type.ljust(45)}\t{srcdata}\t{data}")
+ else:
+ print(f"{event.module.ljust(30)}\t{event_type.ljust(45)}\t{data}")
+
+ if self.opts['_format'] == "csv":
+ print((event.module + d + self.opts['_eventtypes'][event.eventType] + d + srcdata + d + data))
+
+ if self.opts['_format'] == "json":
+ d = event.asDict()
+ d['type'] = self.opts['_eventtypes'][event.eventType]
+ if self.firstEvent:
+ self.firstEvent = False
+ else:
+ print(",")
+ print(json.dumps(d), end='')
+
+ # Handle events sent to this module
+ def handleEvent(self, sfEvent):
+ if sfEvent.eventType == "ROOT":
+ return
+
+ if self.opts['_showonlyrequested']:
+ if sfEvent.eventType in self.opts['_requested']:
+ self.output(sfEvent)
+ else:
+ self.output(sfEvent)
+
+# End of sfp__stor_stdout class
diff --git a/spiderfoot/modules/sfp_abstractapi.py b/spiderfoot/modules/sfp_abstractapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..63513c05e73069765681b8f391e926e843015b50
--- /dev/null
+++ b/spiderfoot/modules/sfp_abstractapi.py
@@ -0,0 +1,355 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_abstractapi
+# Purpose: Search AbstractAPI for domain, phone and IP address information.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 29/07/2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_abstractapi(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AbstractAPI",
+ 'summary': "Look up domain, phone and IP address information from AbstractAPI.",
+ 'flags': ["apikey"],
+ 'useCases': ["Passive", "Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://app.abstractapi.com/",
+ 'model': "FREE_NOAUTH_LIMITED",
+ 'references': [
+ "https://app.abstractapi.com/",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://app.abstractapi.com/users/signup",
+ "Register a free account",
+ "Visit https://app.abstractapi.com/api/",
+ "Visit each API page and click on 'Try it out'",
+ "Your API Key will be listed under 'This is your private API key, specific to this API.'",
+ ],
+ 'favIcon': "https://app.abstractapi.com/favicon.ico",
+ 'logo': "https://app.abstractapi.com/logo192.png",
+ 'description': "Abstract provides powerful APIs to help you enrich any user experience or automate any workflow."
+ }
+ }
+
+ opts = {
+ "companyenrichment_api_key": "",
+ "phonevalidation_api_key": "",
+ "ipgeolocation_api_key": "",
+ }
+
+ optdescs = {
+ "companyenrichment_api_key": "AbstractAPI Company Enrichment API key.",
+ "phonevalidation_api_key": "AbstractAPI Phone Validation API key.",
+ "ipgeolocation_api_key": "AbstractAPI IP Geolocation API key.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "PHONE_NUMBER", "IP_ADDRESS", "IPV6_ADDRESS"]
+
+ def producedEvents(self):
+ return ["COMPANY_NAME", "SOCIAL_MEDIA", "GEOINFO", "PHYSICAL_COORDINATES", "PROVIDER_TELCO", "RAW_RIR_DATA"]
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Abstract API.")
+ return None
+
+ # Rate limited to one request per second
+ if res['code'] == '429':
+ self.error("You are being rate-limited by AbstractAPI.")
+ return None
+
+ if res['code'] == '401':
+ self.error("Unauthorized. Invalid AbstractAPI API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '422':
+ self.error("Usage quota reached. Insufficient API credit.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '500' or res['code'] == '502' or res['code'] == '503':
+ self.error("Abstract API service is unavailable")
+ self.errorState = True
+ return None
+
+ if res['code'] == '204':
+ self.debug("No response data for target")
+ return None
+
+ if res['code'] != '200':
+ self.error(f"Unexpected reply from AbstractAPI: {res['code']}")
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def queryCompanyEnrichment(self, qry):
+ """Enrich domain with company information.
+
+ Args:
+ qry (str): domain name
+
+ Returns:
+ dict: company information
+ """
+
+ api_key = self.opts['companyenrichment_api_key']
+ if not api_key:
+ return None
+
+ params = urllib.parse.urlencode({
+ 'api_key': api_key,
+ 'domain': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://companyenrichment.abstractapi.com/v1/?{params}",
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(1)
+
+ if not res:
+ self.debug("No response from AbstractAPI Company Enrichment API endpoint")
+ return None
+
+ return self.parseApiResponse(res)
+
+ def queryPhoneValidation(self, qry):
+ """Verify phone number and enrich with carrier and location information.
+
+ Args:
+ qry (str): phone number
+
+ Returns:
+ dict: phone number information
+ """
+
+ api_key = self.opts['phonevalidation_api_key']
+ if not api_key:
+ return None
+
+ params = urllib.parse.urlencode({
+ 'api_key': api_key,
+ 'phone': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://phonevalidation.abstractapi.com/v1/?{params}",
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(1)
+
+ if not res:
+ self.debug("No response from AbstractAPI Phone Validation API endpoint")
+ return None
+
+ return self.parseApiResponse(res)
+
+ def queryIpGeolocation(self, qry):
+ """Enrich IP address with geolocation information.
+
+ Args:
+ qry (str): IPv4 address
+
+ Returns:
+ dict: location information
+ """
+
+ api_key = self.opts['ipgeolocation_api_key']
+ if not api_key:
+ return None
+
+ params = urllib.parse.urlencode({
+ 'api_key': api_key,
+ 'ip_address': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://ipgeolocation.abstractapi.com/v1/?{params}",
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(1)
+
+ if not res:
+ self.debug("No response from AbstractAPI Phone Validation API endpoint")
+ return None
+
+ return self.parseApiResponse(res)
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if self.opts["companyenrichment_api_key"] == "" and self.opts["phonevalidation_api_key"] == "" and self.opts["ipgeolocation_api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set any API keys!"
+ )
+ self.errorState = True
+ return
+
+ if eventName not in self.watchedEvents():
+ return
+
+ if eventName == "DOMAIN_NAME":
+ if self.opts["companyenrichment_api_key"] == "":
+ self.info(
+ f"No API key set for Company Enrichment API endpoint. Ignoring {eventData}"
+ )
+ return
+
+ data = self.queryCompanyEnrichment(eventData)
+
+ if not data:
+ return
+
+ name = data.get('name')
+ if not name:
+ return
+
+ if name == 'To Be Confirmed':
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ e = SpiderFootEvent("COMPANY_NAME", name, self.__name__, event)
+ self.notifyListeners(e)
+
+ linkedin_url = data.get('linkedin_url')
+ if linkedin_url:
+ if linkedin_url.startswith('linkedin.com'):
+ linkedin_url = f"https://{linkedin_url}"
+ e = SpiderFootEvent("SOCIAL_MEDIA", f"LinkedIn (Company): {linkedin_url} ", self.__name__, event)
+ self.notifyListeners(e)
+
+ locality = data.get('locality')
+ country = data.get('country')
+ geoinfo = ', '.join(
+ filter(None, [locality, country])
+ )
+
+ if geoinfo:
+ e = SpiderFootEvent("GEOINFO", geoinfo, self.__name__, event)
+ self.notifyListeners(e)
+
+ elif eventName == "PHONE_NUMBER":
+ if self.opts["phonevalidation_api_key"] == "":
+ self.info(
+ f"No API key set for Phone Validation API endpoint. Ignoring {eventData}"
+ )
+ return
+
+ data = self.queryPhoneValidation(eventData)
+
+ if not data:
+ return
+
+ valid = data.get('valid')
+ if not valid:
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ carrier = data.get('carrier')
+ if carrier:
+ e = SpiderFootEvent("PROVIDER_TELCO", carrier, self.__name__, event)
+ self.notifyListeners(e)
+
+ location = data.get('location')
+ country = data.get('country')
+ country_name = None
+ if country:
+ country_name = country.get('name')
+
+ geoinfo = ', '.join(
+ filter(None, [location, country_name])
+ )
+
+ if geoinfo:
+ e = SpiderFootEvent("GEOINFO", geoinfo, self.__name__, event)
+ self.notifyListeners(e)
+
+ elif eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ if self.opts["ipgeolocation_api_key"] == "":
+ self.info(
+ f"No API key set for IP Geolocation API endpoint. Ignoring {eventData}"
+ )
+ return
+
+ data = self.queryIpGeolocation(eventData)
+
+ if not data:
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ geoinfo = ', '.join(
+ [
+ _f for _f in [
+ data.get('city'),
+ data.get('region'),
+ data.get('postal_code'),
+ data.get('country'),
+ data.get('continent'),
+ ] if _f
+ ]
+ )
+
+ if geoinfo:
+ e = SpiderFootEvent("GEOINFO", geoinfo, self.__name__, event)
+ self.notifyListeners(e)
+
+ latitude = data.get('latitude')
+ longitude = data.get('longitude')
+ if latitude and longitude:
+ e = SpiderFootEvent("PHYSICAL_COORDINATES", f"{latitude}, {longitude}", self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_abstractapi class
diff --git a/spiderfoot/modules/sfp_abusech.py b/spiderfoot/modules/sfp_abusech.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e655b3594b60d2c5bbc67f0fc2cd2a63f291b28
--- /dev/null
+++ b/spiderfoot/modules/sfp_abusech.py
@@ -0,0 +1,415 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_abusech
+# Purpose: Check if a host/domain, IP address or netblock is malicious according
+# to Abuse.ch.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_abusech(SpiderFootPlugin):
+
+ meta = {
+ 'name': "abuse.ch",
+ 'summary': "Check if a host/domain, IP address or netblock is malicious according to Abuse.ch.",
+ 'flags': [],
+ 'useCases': ["Passive", "Investigate"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.abuse.ch",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://feodotracker.abuse.ch/",
+ "https://sslbl.abuse.ch/",
+ "https://urlhaus.abuse.ch/",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://bazaar.abuse.ch/api#api_key",
+ "Login using a Twitter Account",
+ "Navigate to 'Account Settings'",
+ "The API key is listed under 'Your API Key'",
+ "Visit https://urlhaus.abuse.ch/api/",
+ "Login using a Twitter Account at https://urlhaus.abuse.ch/login/",
+ "Navigate to https://urlhaus.abuse.ch/api/#account",
+ "The API Key is listed under 'API-Key'"
+ ],
+ 'favIcon': "https://abuse.ch/favicon.ico",
+ 'logo': "https://abuse.ch/images/abusech.svg",
+ 'description': "abuse.ch is operated by a random swiss guy fighting malware for non-profit, "
+ "running a couple of projects helping internet service providers and "
+ "network operators protecting their infrastructure from malware.\n"
+ "IT-Security researchers, vendors and law enforcement agencies rely on data from abuse.ch,"
+ "trying to make the internet a safer place.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'abusefeodoip': True,
+ 'abusesslblip': True,
+ 'abuseurlhaus': True,
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'abusefeodoip': "Enable abuse.ch Feodo IP check?",
+ 'abusesslblip': "Enable abuse.ch SSL Backlist IP check?",
+ 'abuseurlhaus': "Enable abuse.ch URLhaus check?",
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "IP_ADDRESS",
+ "NETBLOCK_MEMBER",
+ "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_IPADDR",
+ "CO_HOSTED_SITE",
+ "NETBLOCK_OWNER"
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_COHOST",
+ "MALICIOUS_NETBLOCK"
+ ]
+
+ def queryFeodoTrackerBlacklist(self, target, targetType):
+ blacklist = self.retrieveFeodoTrackerBlacklist()
+
+ if not blacklist:
+ return False
+
+ if targetType == "ip":
+ if target in blacklist:
+ self.debug(f"IP address {target} found in Abuse.ch Feodo Tracker.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in blacklist:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in Abuse.ch Feodo Tracker.")
+ return True
+
+ return False
+
+ def retrieveFeodoTrackerBlacklist(self):
+ blacklist = self.sf.cacheGet('abusech_feodo', 24)
+
+ if blacklist is not None:
+ return self.parseFeodoTrackerBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://feodotracker.abuse.ch/downloads/ipblocklist.txt",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from Abuse.ch Abuse.ch Feodo Tracker.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from Abuse.ch Feodo Tracker")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("abusech_feodo", res['content'])
+
+ return self.parseFeodoTrackerBlacklist(res['content'])
+
+ def parseFeodoTrackerBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from Abuse.ch Feodo Tracker
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ if not blacklist:
+ return ips
+
+ for ip in blacklist.split('\n'):
+ ip = ip.strip()
+ if not ip:
+ continue
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def querySslBlacklist(self, target, targetType):
+ blacklist = self.retrieveSslBlacklist()
+
+ if not blacklist:
+ return False
+
+ if targetType == "ip":
+ if target in blacklist:
+ self.debug(f"IP address {target} found in Abuse.ch SSL Blacklist.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in blacklist:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in Abuse.ch SSL Blacklist.")
+ return True
+
+ return False
+
+ def retrieveSslBlacklist(self):
+ blacklist = self.sf.cacheGet('abusech_ssl', 24)
+
+ if blacklist is not None:
+ return self.parseSslBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://sslbl.abuse.ch/blacklist/sslipblacklist.csv",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from Abuse.ch Abuse.ch Feodo Tracker.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from Abuse.ch Feodo Tracker")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("abusech_ssl", res['content'])
+
+ return self.parseSslBlacklist(res['content'])
+
+ def parseSslBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): CSV blacklist from Abuse.ch SSL Blacklist
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ if not blacklist:
+ return ips
+
+ for line in blacklist.split('\n'):
+ line = line.strip()
+ if not line:
+ continue
+ if line.startswith('#'):
+ continue
+ csv = line.split(',')
+ if len(csv) < 2:
+ continue
+ ip = csv[1]
+ if not self.sf.validIP(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def queryUrlHausBlacklist(self, target, targetType):
+ blacklist = self.retrieveUrlHausBlacklist()
+
+ if not blacklist:
+ return False
+
+ if targetType == "ip":
+ if target in blacklist:
+ self.debug(f"IP address {target} found in Abuse.ch URL Haus Blacklist.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in blacklist:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in Abuse.ch URL Haus Blacklist.")
+ return True
+ elif targetType == "domain":
+ if target.lower() in blacklist:
+ self.debug(f"Host name {target} found in Abuse.ch URL Haus Blacklist.")
+ return True
+
+ return False
+
+ def retrieveUrlHausBlacklist(self):
+ blacklist = self.sf.cacheGet('abusech_urlhaus', 24)
+
+ if blacklist is not None:
+ return self.parseUrlHausBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://urlhaus.abuse.ch/downloads/csv_recent/",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from Abuse.ch URL Haus.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from Abuse.ch URL Haus")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("abusech_urlhaus", res['content'])
+
+ return self.parseUrlHausBlacklist(res['content'])
+
+ def parseUrlHausBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from Abuse.ch URL Haus
+
+ Returns:
+ list: list of blacklisted hosts
+ """
+ hosts = list()
+
+ if not blacklist:
+ return hosts
+
+ for line in blacklist.split('\n'):
+ if not line:
+ continue
+ if line.startswith('#'):
+ continue
+
+ # Note: URL parsing and validation with sf.validHost() is too slow to use here
+ url = line.strip().lower()
+ if len(url.split("/")) < 3:
+ continue
+ host = url.split("/")[2].split(':')[0]
+ if not host:
+ continue
+ if "." not in host:
+ continue
+ hosts.append(host)
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ evtType = 'MALICIOUS_IPADDR'
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ evtType = 'MALICIOUS_NETBLOCK'
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ evtType = 'MALICIOUS_SUBNET'
+ elif eventName == "INTERNET_NAME":
+ targetType = 'domain'
+ evtType = "MALICIOUS_INTERNET_NAME"
+ elif eventName == 'AFFILIATE_INTERNET_NAME':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'domain'
+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'
+ elif eventName == 'CO_HOSTED_SITE':
+ if not self.opts.get('checkcohosts', False):
+ return
+ targetType = 'domain'
+ evtType = 'MALICIOUS_COHOST'
+ else:
+ return
+
+ if targetType in ['ip', 'netblock']:
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with Abuse.ch Feodo Tracker")
+ if self.queryFeodoTrackerBlacklist(eventData, targetType):
+ url = "https://feodotracker.abuse.ch/downloads/ipblocklist.txt"
+ text = f"Abuse.ch Feodo Tracker [{eventData}]\n{url} "
+ evt = SpiderFootEvent(evtType, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with Abuse.ch SSL Blacklist")
+ if self.querySslBlacklist(eventData, targetType):
+ url = "https://sslbl.abuse.ch/blacklist/sslipblacklist.csv"
+ text = f"Abuse.ch SSL Blacklist [{eventData}]\n{url} "
+ evt = SpiderFootEvent(evtType, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if targetType in ['ip', 'domain']:
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with Abuse.ch URL Haus")
+ if self.queryUrlHausBlacklist(eventData, targetType):
+ url = "https://urlhaus.abuse.ch/downloads/csv_recent/"
+ text = f"Abuse.ch URL Haus Blacklist [{eventData}]\n{url} "
+ evt = SpiderFootEvent(evtType, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_abusech class
diff --git a/spiderfoot/modules/sfp_abuseipdb.py b/spiderfoot/modules/sfp_abuseipdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f70f8785d6ee973c71f3da37fe1eea9447dddb9
--- /dev/null
+++ b/spiderfoot/modules/sfp_abuseipdb.py
@@ -0,0 +1,341 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_abuseipdb
+# Purpose: Check if an IP address is malicious according to AbuseIPDB.com.
+#
+# Author: steve@binarypool.com
+#
+# Created: 06/09/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_abuseipdb(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AbuseIPDB",
+ 'summary': "Check if an IP address is malicious according to AbuseIPDB.com blacklist.",
+ 'flags': ["apikey"],
+ 'useCases': ["Passive", "Investigate"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.abuseipdb.com",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.abuseipdb.com/#introduction",
+ "https://www.abuseipdb.com/fail2ban.html",
+ "https://www.abuseipdb.com/csf",
+ "https://www.abuseipdb.com/suricata",
+ "https://www.abuseipdb.com/splunk",
+ "https://www.abuseipdb.com/categories"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.abuseipdb.com/pricing",
+ "Select the plan required",
+ "Register a new account with an email",
+ "Navigate to https://www.abuseipdb.com/account/api",
+ "The API Key is listed under 'Keys'"
+ ],
+ 'favIcon': "https://www.abuseipdb.com/favicon.ico",
+ 'logo': "https://www.abuseipdb.com/img/abuseipdb.png.pagespeed.ce.CI8T6WsXU7.png",
+ 'description': "AbuseIPDB is a project dedicated to helping combat the spread of hackers,"
+ "spammers, and abusive activity on the internet.\n"
+ "Our mission is to help make Web safer by providing a central blacklist for"
+ "webmasters, system administrators, and other interested parties to"
+ "report and find IP addresses that have been associated with malicious activity online."
+ }
+ }
+
+ opts = {
+ 'api_key': '',
+ 'confidenceminimum': 90,
+ 'checkaffiliates': True,
+ 'limit': 10000
+ }
+
+ optdescs = {
+ 'api_key': "AbuseIPDB.com API key.",
+ 'confidenceminimum': "The minimium AbuseIPDB confidence level to require.",
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'limit': 'Maximum number of results to retrieve.',
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ ]
+
+ def queryBlacklist(self):
+ blacklist = self.sf.cacheGet('abuseipdb', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': "text/plain"
+ }
+
+ params = urllib.parse.urlencode({
+ 'confidenceMinimum': self.opts['confidenceminimum'],
+ 'limit': self.opts['limit'],
+ 'plaintext': '1'
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/blacklist?{params}",
+ timeout=60, # retrieving 10,000 results (default) or more can sometimes take a while
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.error(f"Error retrieving search results, code {res['code']}")
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.error("Error retrieving search results from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("abuseipdb", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from AbuseIPDB
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ if not blacklist:
+ return ips
+
+ for ip in blacklist.split('\n'):
+ ip = ip.strip()
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip) and not self.sf.validIP6(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def queryIpAddress(self, ip):
+ """Query API for an IPv4 or IPv6 address.
+
+ Note: Currently unused.
+
+ Args:
+ ip (str): IP address
+
+ Returns:
+ str: API response as JSON
+ """
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': 'application/json',
+ }
+
+ params = urllib.parse.urlencode({
+ 'ipAddress': ip,
+ 'maxAgeInDays': 30,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/check?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.error("Error retrieving search results from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ return None
+
+ def queryNetblock(self, ip):
+ """Query API for a netblock.
+
+ Note: Currently unused.
+
+ Args:
+ ip (str): CIDR range
+
+ Returns:
+ str: API response as JSON
+ """
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': 'application/json',
+ }
+
+ params = urllib.parse.urlencode({
+ 'ipAddress': ip,
+ 'maxAgeInDays': 30,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/check-block?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.error("Error retrieving search results from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from AbuseIPDB")
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:
+ return
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ blacklist_type = "BLACKLISTED_IPADDR"
+ malicious_type = 'MALICIOUS_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ malicious_type = 'MALICIOUS_AFFILIATE_IPADDR'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of IP address {eventData} with AbuseIPDB")
+
+ blacklist = self.queryBlacklist()
+
+ if not blacklist:
+ return
+
+ if eventData not in blacklist:
+ return
+
+ self.info(f"Malicious IP address {eventData} found in AbuseIPDB blacklist")
+
+ url = f"https://www.abuseipdb.com/check/{eventData}"
+
+ evt = SpiderFootEvent(
+ malicious_type,
+ f"AbuseIPDB [{eventData}]\n{url} ",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(
+ blacklist_type,
+ f"AbuseIPDB [{eventData}]\n{url} ",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_abuseipdb class
diff --git a/spiderfoot/modules/sfp_abusix.py b/spiderfoot/modules/sfp_abusix.py
new file mode 100644
index 0000000000000000000000000000000000000000..aad836d49b29345f9ef58261b8fcb8250506ebaa
--- /dev/null
+++ b/spiderfoot/modules/sfp_abusix.py
@@ -0,0 +1,289 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_abusix
+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains
+# appear in the Abusix Mail Intelligence blacklist.
+#
+# Author:
+#
+# Created: 2021-10-17
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import ipaddress
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_abusix(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Abusix Mail Intelligence",
+ 'summary': "Check if a netblock or IP address is in the Abusix Mail Intelligence blacklist.",
+ 'flags': ['apikey'],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://abusix.org/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://abusix.com/products/abusix-mail-intelligence/",
+ "https://docs.abusix.com/105726-setup-abusix-mail-intelligence/ami%2Fsetup%2Fexample-queries",
+ "https://docs.abusix.com/105725-detailed-list-information/ami%2Freturn-codes",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://app.abusix.com/signup",
+ "Register a free account",
+ "Browse to 'Account Settings' page",
+ "The API key is listed on the 'Email protection' page."
+ ],
+ 'logo': "https://abusix.com/wp-content/uploads/2020/10/Footer_logo.png",
+ 'description': "Abusix Mail Intelligence is an innovative set of blocklists (RBL/DNSBL) "
+ "that adds real-time threat data to your existing email protection. "
+ "Considered as the first line of defense, blocklists help to prevent email-borne threats "
+ "such as spam and malware from entering your network."
+ }
+ }
+
+ opts = {
+ 'api_key': "",
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxv6netblock': 120,
+ 'subnetlookup': True,
+ 'maxsubnet': 24,
+ 'maxv6subnet': 120,
+ }
+
+ optdescs = {
+ 'api_key': "Abusix Mail Intelligence API key.",
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6netblock': "If looking up owned netblocks, the maximum IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6subnet': "If looking up subnets, the maximum IPv6 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ }
+
+ results = None
+ errorState = False
+
+ checks = {
+ "127.0.0.2": "black",
+ "127.0.0.3": "black (composite/heuristic)",
+ "127.0.0.4": "exploit / authbl",
+ "127.0.0.5": "forged",
+ "127.0.0.6": "backscatter",
+ "127.0.0.11": "policy (generic rDNS)",
+ "127.0.0.12": "policy (missing rDNS)",
+ "127.0.0.100": "noip",
+ "127.0.1.1": "dblack",
+ "127.0.1.2": "dblack (Newly Observed Domain)",
+ "127.0.1.3": "dblack (Unshortened)",
+ "127.0.2.1": "white",
+ "127.0.3.1": "shorthash",
+ "127.0.3.2": "diskhash",
+ "127.0.4.1": "btc-wallets",
+ "127.0.5.1": "attachhash",
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'IPV6_ADDRESS',
+ 'AFFILIATE_IPADDR',
+ 'AFFILIATE_IPV6_ADDRESS',
+ "NETBLOCK_MEMBER",
+ "NETBLOCKV6_MEMBER",
+ "NETBLOCK_OWNER",
+ "NETBLOCKV6_OWNER",
+ 'INTERNET_NAME',
+ 'AFFILIATE_INTERNET_NAME',
+ 'CO_HOSTED_SITE',
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def reverseIpAddress(self, ipaddr):
+ if not self.sf.validIP(ipaddr):
+ self.debug(f"Invalid IPv4 address {ipaddr}")
+ return None
+ return ipaddress.ip_address(ipaddr).reverse_pointer.replace('.in-addr.arpa', '')
+
+ def reverseIp6Address(self, ipaddr):
+ if not self.sf.validIP6(ipaddr):
+ self.debug(f"Invalid IPv6 address {ipaddr}")
+ return None
+ return ipaddress.ip_address(ipaddr).reverse_pointer.replace('.ip6.arpa', '')
+
+ def query(self, qaddr):
+ """Query Abusix Mail Intelligence DNS.
+
+ Args:
+ qaddr (str): Host name or IPv4 address.
+
+ Returns:
+ list: Abusix DNS entries
+ """
+ if self.sf.validIP(qaddr):
+ lookup = f"{self.reverseIpAddress(qaddr)}.{self.opts['api_key']}.combined.mail.abusix.zone"
+ elif self.sf.validIP6(qaddr):
+ lookup = f"{self.reverseIp6Address(qaddr)}.{self.opts['api_key']}.combined.mail.abusix.zone"
+ else:
+ lookup = f"{qaddr}.{self.opts['api_key']}.combined.mail.abusix.zone"
+
+ self.debug(f"Checking Abusix Mail Intelligence blacklist: {lookup}")
+
+ try:
+ return self.sf.resolveHost(lookup)
+ except Exception as e:
+ self.debug(f"Abusix Mail Intelligence did not resolve {qaddr} / {lookup}: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if not self.opts['api_key']:
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName in ['NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ if not self.opts['subnetlookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_MEMBER':
+ max_subnet = self.opts['maxv6subnet']
+ else:
+ max_subnet = self.opts['maxsubnet']
+
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ elif eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts['netblocklookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_OWNER':
+ max_netblock = self.opts['maxv6netblock']
+ else:
+ max_netblock = self.opts['maxnetblock']
+
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ addrs = list()
+ if eventName.startswith("NETBLOCK"):
+ for addr in IPNetwork(eventData):
+ addrs.append(str(addr))
+ else:
+ addrs.append(eventData)
+
+ for addr in addrs:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ res = self.query(addr)
+
+ self.results[addr] = True
+
+ if not res:
+ continue
+
+ self.debug(f"{addr} found in Abusix Mail Intelligence DNS")
+
+ for result in res:
+ k = str(result)
+
+ if k not in self.checks:
+ if 'mail.abusix.zone' not in result:
+ # This is an error. The "checks" dict may need to be updated.
+ self.error(f"Abusix Mail Intelligence resolved address {addr} to unknown IP address {result} not found in Abusix Mail Intelligence list.")
+ continue
+
+ text = f"Abusix Mail Intelligence - {self.checks[k]} [{addr}]\nhttps://lookup.abusix.com/search?q={addr} "
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_abusix class
diff --git a/spiderfoot/modules/sfp_accounts.py b/spiderfoot/modules/sfp_accounts.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea60858213d02ae4a79108015fa4664863e636f4
--- /dev/null
+++ b/spiderfoot/modules/sfp_accounts.py
@@ -0,0 +1,409 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_accounts
+# Purpose: Identify the existence of a given acount on various sites thanks
+# to Micah Hoffman's (https://github.com/WebBreacher) list.
+#
+# Author: Steve Micallef
+#
+# Created: 18/02/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import random
+import threading
+import time
+from queue import Empty as QueueEmpty
+from queue import Queue
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_accounts(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Account Finder",
+ 'summary': "Look for possible associated accounts on over 500 social and other websites such as Instagram, Reddit, etc.",
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Social Media"]
+ }
+
+ # Default options
+ opts = {
+ "ignorenamedict": True,
+ "ignoreworddict": True,
+ "musthavename": True,
+ "userfromemail": True,
+ "permutate": False,
+ "usernamesize": 4,
+ "_maxthreads": 20
+ }
+
+ # Option descriptions
+ optdescs = {
+ "ignorenamedict": "Don't bother looking up names that are just stand-alone first names (too many false positives).",
+ "ignoreworddict": "Don't bother looking up names that appear in the dictionary.",
+ "musthavename": "The username must be mentioned on the social media page to consider it valid (helps avoid false positives).",
+ "userfromemail": "Extract usernames from e-mail addresses at all? If disabled this can reduce false positives for common usernames but for highly unique usernames it would result in missed accounts.",
+ "permutate": "Look for the existence of account name permutations. Useful to identify fraudulent social media accounts or account squatting.",
+ "usernamesize": "The minimum length of a username to query across social media sites. Helps avoid false positives for very common short usernames.",
+ "_maxthreads": "Maximum threads"
+ }
+
+ results = None
+ reportedUsers = list()
+ siteResults = dict()
+ sites = list()
+ errorState = False
+ distrustedChecked = False
+ lock = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.commonNames = list()
+ self.reportedUsers = list()
+ self.errorState = False
+ self.distrustedChecked = False
+ self.__dataSource__ = "Social Media"
+ self.lock = threading.Lock()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ self.commonNames = SpiderFootHelpers.humanNamesFromWordlists()
+ self.words = SpiderFootHelpers.dictionaryWordsFromWordlists()
+
+ content = self.sf.cacheGet("sfaccountsv2", 48)
+ if content is None:
+ url = "https://raw.githubusercontent.com/WebBreacher/WhatsMyName/main/wmn-data.json"
+ data = self.sf.fetchUrl(url, useragent="SpiderFoot")
+
+ if data['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return
+
+ content = data['content']
+ self.sf.cachePut("sfaccountsv2", content)
+
+ try:
+ self.sites = [site for site in json.loads(content)['sites'] if not site.get('valid', True) is False]
+ except Exception as e:
+ self.error(f"Unable to parse social media accounts list: {e}")
+ self.errorState = True
+ return
+
+ def watchedEvents(self):
+ return ["EMAILADDR", "DOMAIN_NAME", "HUMAN_NAME", "USERNAME"]
+
+ def producedEvents(self):
+ return ["USERNAME", "ACCOUNT_EXTERNAL_OWNED",
+ "SIMILAR_ACCOUNT_EXTERNAL"]
+
+ def checkSite(self, name, site):
+ if 'uri_check' not in site:
+ return
+
+ url = site['uri_check'].format(account=name)
+ if 'uri_pretty' in site:
+ ret_url = site['uri_pretty'].format(account=name)
+ else:
+ ret_url = url
+ retname = f"{site['name']} (Category: {site['cat']})\n{ret_url} "
+
+ post = None
+ if site.get('post_body'):
+ post = site['post_body']
+
+ res = self.sf.fetchUrl(
+ url,
+ postData=post,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ noLog=True,
+ verify=False
+ )
+
+ if not res['content']:
+ with self.lock:
+ self.siteResults[retname] = False
+ return
+
+ if site.get('e_code') != site.get('m_code'):
+ if res['code'] != str(site.get('e_code')):
+ with self.lock:
+ self.siteResults[retname] = False
+ return
+
+ if site.get('e_string') not in res['content'] or (site.get('m_string') and site.get('m_string') in res['content']):
+ with self.lock:
+ self.siteResults[retname] = False
+ return
+
+ if self.opts['musthavename']:
+ if name.lower() not in res['content'].lower():
+ self.debug(f"Skipping {site['name']} as username not mentioned.")
+ with self.lock:
+ self.siteResults[retname] = False
+ return
+
+ # Some sites can't handle periods so treat bob.abc and bob as the same
+ # TODO: fix this once WhatsMyName has support for usernames with '.'
+ if "." in name:
+ firstname = name.split(".")[0]
+ if firstname + "<" in res['content'] or firstname + '"' in res['content']:
+ with self.lock:
+ self.siteResults[retname] = False
+ return
+
+ with self.lock:
+ self.siteResults[retname] = True
+
+ def checkSites(self, username, sites=None):
+ def processSiteQueue(username, queue):
+ try:
+ while True:
+ site = queue.get(timeout=0.1)
+ try:
+ self.checkSite(username, site)
+ except Exception as e:
+ self.debug(f'Thread {threading.current_thread().name} exception: {e}')
+ except QueueEmpty:
+ return
+
+ startTime = time.monotonic()
+
+ # results will be collected in siteResults
+ self.siteResults = {}
+
+ sites = self.sites if sites is None else sites
+
+ # load the queue
+ queue = Queue()
+ for site in sites:
+ queue.put(site)
+
+ # start the scan threads
+ threads = []
+ for i in range(min(len(sites), self.opts['_maxthreads'])):
+ thread = threading.Thread(
+ name=f'sfp_accounts_scan_{i}',
+ target=processSiteQueue,
+ args=(username, queue))
+ thread.start()
+ threads.append(thread)
+
+ # wait for all scan threads to finish
+ while threads:
+ threads.pop(0).join()
+
+ duration = time.monotonic() - startTime
+ scanRate = len(sites) / duration
+ self.debug(f'Scan statistics: name={username}, count={len(self.siteResults)}, duration={duration:.2f}, rate={scanRate:.0f}')
+
+ return [site for site, found in self.siteResults.items() if found]
+
+ def generatePermutations(self, username):
+ permutations = list()
+ prefixsuffix = ['_', '-']
+ replacements = {
+ 'a': ['4', 's'],
+ 'b': ['v', 'n'],
+ 'c': ['x', 'v'],
+ 'd': ['s', 'f'],
+ 'e': ['w', 'r'],
+ 'f': ['d', 'g'],
+ 'g': ['f', 'h'],
+ 'h': ['g', 'j', 'n'],
+ 'i': ['o', 'u', '1'],
+ 'j': ['k', 'h', 'i'],
+ 'k': ['l', 'j'],
+ 'l': ['i', '1', 'k'],
+ 'm': ['n'],
+ 'n': ['m'],
+ 'o': ['p', 'i', '0'],
+ 'p': ['o', 'q'],
+ 'r': ['t', 'e'],
+ 's': ['a', 'd', '5'],
+ 't': ['7', 'y', 'z', 'r'],
+ 'u': ['v', 'i', 'y', 'z'],
+ 'v': ['u', 'c', 'b'],
+ 'w': ['v', 'vv', 'q', 'e'],
+ 'x': ['z', 'y', 'c'],
+ 'y': ['z', 'x'],
+ 'z': ['y', 'x'],
+ '0': ['o'],
+ '1': ['l'],
+ '2': ['5'],
+ '3': ['e'],
+ '4': ['a'],
+ '5': ['s'],
+ '6': ['b'],
+ '7': ['t'],
+ '8': ['b'],
+ '9': []
+ }
+ pairs = {
+ 'oo': ['00'],
+ 'll': ['l1l', 'l1l', '111', '11'],
+ '11': ['ll', 'lll', 'l1l', '1l1']
+ }
+
+ # Generate a set with replacements, then
+ # add suffixes and prefixes.
+ pos = 0
+ for c in username:
+ if c not in replacements:
+ continue
+ if len(replacements[c]) == 0:
+ continue
+ npos = pos + 1
+ for xc in replacements[c]:
+ newuser = username[0:pos] + xc + username[npos:len(username)]
+ permutations.append(newuser)
+
+ pos += 1
+
+ # Search for common double-letter replacements
+ for p in pairs:
+ if p in username:
+ for r in pairs[p]:
+ permutations.append(username.replace(p, r))
+
+ # Search for prefixed and suffixed usernames
+ for c in prefixsuffix:
+ permutations.append(username + c)
+ permutations.append(c + username)
+
+ # Search for double character usernames
+ pos = 0
+ for c in username:
+ permutations.append(username[0:pos] + c + c + username[(pos + 1):len(username)])
+ pos += 1
+
+ return list(set(permutations))
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ users = list()
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Skip events coming from me unless they are USERNAME events
+ if eventName != "USERNAME" and srcModuleName == "sfp_accounts":
+ self.debug(f"Ignoring {eventName}, from self.")
+ return
+
+ if eventData in list(self.results.keys()):
+ return
+
+ self.results[eventData] = True
+
+ # If being called for the first time, let's see how trusted the
+ # sites are by attempting to fetch a garbage user.
+ if not self.distrustedChecked:
+ # Check if a state cache exists first, to not have to do this all the time
+ content = self.sf.cacheGet("sfaccounts_state_v3", 72)
+ if content:
+ if content != "None": # "None" is written to the cached file when no sites are distrusted
+ delsites = list()
+ for line in content.split("\n"):
+ if line == '':
+ continue
+ delsites.append(line)
+ self.sites = [d for d in self.sites if d['name'] not in delsites]
+ else:
+ randpool = 'abcdefghijklmnopqrstuvwxyz1234567890'
+ randuser = ''.join([random.SystemRandom().choice(randpool) for x in range(10)])
+ res = self.checkSites(randuser)
+ if res:
+ delsites = list()
+ for site in res:
+ sitename = site.split(" (Category:")[0]
+ self.debug(f"Distrusting {sitename}")
+ delsites.append(sitename)
+ self.sites = [d for d in self.sites if d['name'] not in delsites]
+ else:
+ # The caching code needs *some* content
+ delsites = "None"
+ self.sf.cachePut("sfaccounts_state_v3", delsites)
+
+ self.distrustedChecked = True
+
+ if eventName == "HUMAN_NAME":
+ names = [eventData.lower().replace(" ", ""), eventData.lower().replace(" ", ".")]
+ for name in names:
+ users.append(name)
+
+ if eventName == "DOMAIN_NAME":
+ kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ if not kw:
+ return
+
+ users.append(kw)
+
+ if eventName == "EMAILADDR" and self.opts['userfromemail']:
+ name = eventData.split("@")[0].lower()
+ users.append(name)
+
+ if eventName == "USERNAME":
+ users.append(eventData)
+
+ for user in set(users):
+ if user in self.opts['_genericusers'].split(","):
+ self.debug(f"{user} is a generic account name, skipping.")
+ continue
+
+ if self.opts['ignorenamedict'] and user in self.commonNames:
+ self.debug(f"{user} is found in our name dictionary, skipping.")
+ continue
+
+ if self.opts['ignoreworddict'] and user in self.words:
+ self.debug(f"{user} is found in our word dictionary, skipping.")
+ continue
+
+ if user not in self.reportedUsers and eventData != user:
+ if len(user) < self.opts['usernamesize']:
+ self.debug(f"{user} is too short, skipping.")
+ continue
+
+ evt = SpiderFootEvent("USERNAME", user, self.__name__, event)
+ self.notifyListeners(evt)
+ self.reportedUsers.append(user)
+
+ # Only look up accounts when we've received a USERNAME event (possibly from
+ # ourselves), since we want them to have gone through some verification by
+ # this module, and we don't want duplicates (one based on EMAILADDR and another
+ # based on USERNAME).
+ if eventName == "USERNAME":
+ res = self.checkSites(user)
+ for site in res:
+ evt = SpiderFootEvent(
+ "ACCOUNT_EXTERNAL_OWNED",
+ site,
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ if self.opts['permutate']:
+ permutations = self.generatePermutations(user)
+ for puser in permutations:
+ res = self.checkSites(puser)
+ for site in res:
+ evt = SpiderFootEvent(
+ "SIMILAR_ACCOUNT_EXTERNAL",
+ site,
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+# End of sfp_accounts class
diff --git a/spiderfoot/modules/sfp_adblock.py b/spiderfoot/modules/sfp_adblock.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1c9ff8c9cc7e55620e437fffffbad3e1660bd0b
--- /dev/null
+++ b/spiderfoot/modules/sfp_adblock.py
@@ -0,0 +1,175 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_adblock
+# Purpose: SpiderFoot plug-in to test if external/internally linked pages
+# would be blocked by AdBlock Plus.
+#
+# Author: Steve Micallef
+#
+# Created: 22/09/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import adblockparser
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_adblock(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AdBlock Check",
+ 'summary': "Check if linked pages would be blocked by AdBlock Plus.",
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://adblockplus.org/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://help.eyeo.com/en/adblockplus/",
+ "https://adblockplus.org/en/download",
+ "https://adblockplus.org/en/filters#options",
+ "https://chrome.google.com/webstore/detail/adblock-plus-free-ad-bloc/cfhdojbkjhnklbpkdaibdccddilifddb"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://adblockplus.org/en/",
+ 'logo': "https://adblockplus.org/img/navbar-logo.svg",
+ 'description': "Adblock Plus is a free extension that allows you to customize your web experience."
+ "You can block annoying ads, disable tracking and lots more."
+ "It’s available for all major desktop browsers and for your mobile devices.\n"
+ "Block ads that interrupt your browsing experience."
+ "Say goodbye to video ads, pop-ups, flashing banners and more."
+ "Blocking these annoyances means pages load faster.\n"
+ "With Adblock Plus avoiding tracking and malware is easy."
+ "Blocking intrusive ads reduces the risk of \"malvertising\" infections."
+ "Blocking tracking stops companies following your online activity."
+ }
+ }
+
+ # Default options
+ opts = {
+ "blocklist": "https://easylist-downloads.adblockplus.org/easylist.txt",
+ 'cacheperiod': 24,
+ }
+
+ optdescs = {
+ "blocklist": "AdBlockPlus block list.",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ }
+
+ results = None
+ rules = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.rules = None
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL", "LINKED_URL_EXTERNAL", "PROVIDER_JAVASCRIPT"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["URL_ADBLOCKED_INTERNAL", "URL_ADBLOCKED_EXTERNAL"]
+
+ def retrieveBlocklist(self, blocklist_url):
+ if not blocklist_url:
+ return None
+
+ blocklist = self.sf.cacheGet(f"adblock_{blocklist_url}", 24)
+
+ if blocklist is not None:
+ return self.setBlocklistRules(blocklist)
+
+ res = self.sf.fetchUrl(blocklist_url, timeout=30)
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} for {blocklist_url}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error(f"Unable to download AdBlock Plus blocklist: {blocklist_url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut(f"adblock_{blocklist_url}", res['content'])
+
+ return self.setBlocklistRules(res['content'])
+
+ def setBlocklistRules(self, blocklist):
+ """Parse AdBlock Plus blocklist and set blocklist rules
+
+ Args:
+ blocklist (str): plaintext AdBlock Plus blocklist
+ """
+ if not blocklist:
+ return
+
+ lines = blocklist.split('\n')
+ self.debug(f"Retrieved {len(lines)} AdBlock blocklist rules")
+ try:
+ self.rules = adblockparser.AdblockRules(lines)
+ except adblockparser.AdblockParsingError as e:
+ self.errorState = True
+ self.error(f"Parsing error handling AdBlock list: {e}")
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug("Already checked this URL for AdBlock matching, skipping.")
+ return
+
+ self.results[eventData] = True
+
+ if self.errorState:
+ return
+
+ if not self.opts["blocklist"]:
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set a blocklist URL!"
+ )
+ self.errorState = True
+ return
+
+ if not self.rules:
+ self.retrieveBlocklist(self.opts['blocklist'])
+
+ if not self.rules:
+ self.error("No AdBlock Plus rules loaded")
+ self.errorState = True
+ return
+
+ try:
+ if eventName == 'PROVIDER_JAVASCRIPT':
+ if self.rules and self.rules.should_block(eventData, {'third-party': True, 'script': True}):
+ evt = SpiderFootEvent("URL_ADBLOCKED_EXTERNAL", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == 'LINKED_URL_EXTERNAL':
+ if self.rules and self.rules.should_block(eventData, {'third-party': True}):
+ evt = SpiderFootEvent("URL_ADBLOCKED_EXTERNAL", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == 'LINKED_URL_INTERNAL':
+ if self.rules and self.rules.should_block(eventData):
+ evt = SpiderFootEvent("URL_ADBLOCKED_INTERNAL", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ except ValueError as e:
+ self.error(f"Parsing error handling AdBlock list: {e}")
+ self.errorState = True
+
+# End of sfp_adblock class
diff --git a/spiderfoot/modules/sfp_adguard_dns.py b/spiderfoot/modules/sfp_adguard_dns.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a7d287f42807a7a3ceb803000a469210a5f6fe7
--- /dev/null
+++ b/spiderfoot/modules/sfp_adguard_dns.py
@@ -0,0 +1,129 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_adguard_dns
+# Purpose: SpiderFoot plug-in for looking up whether hosts are blocked by
+# AdGuard DNS servers.
+#
+# Author:
+#
+# Created: 2021-10-11
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_adguard_dns(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AdGuard DNS",
+ 'summary': "Check if a host would be blocked by AdGuard DNS.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://adguard.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://adguard.com/en/adguard-dns/overview.html",
+ ],
+ 'favIcon': "https://adguard.com/img/favicons/favicon.ico",
+ 'logo': "https://adguard.com/img/favicons/apple-touch-icon.png",
+ 'description': "AdGuard DNS is a foolproof way to block Internet ads that does not require installing any applications. "
+ "It is easy to use, absolutely free, easily set up on any device, and provides you with minimal necessary functions "
+ "to block ads, counters, malicious websites, and adult content."
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ ]
+
+ def queryDefaultDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["94.140.14.14", "94.140.15.15"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def queryFamilyDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["94.140.14.15", "94.140.15.16"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ family = self.sf.normalizeDNS(self.queryFamilyDNS(eventData))
+ default = self.sf.normalizeDNS(self.queryDefaultDNS(eventData))
+
+ if not family or not default:
+ return
+
+ if '94.140.14.35' in family:
+ self.debug(f"{eventData} blocked by AdGuard Family DNS")
+ evt = SpiderFootEvent(blacklist_type, f"AdGuard - Family Filter [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if '94.140.14.35' in default:
+ self.debug(f"{eventData} blocked by AdGuard Default DNS")
+ evt = SpiderFootEvent(blacklist_type, f"AdGuard - Default Filter [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_adguard_dns class
diff --git a/spiderfoot/modules/sfp_ahmia.py b/spiderfoot/modules/sfp_ahmia.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d023575f8d94d4e3e1d776ae86df4b44f52bc69
--- /dev/null
+++ b/spiderfoot/modules/sfp_ahmia.py
@@ -0,0 +1,174 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ahmia
+# Purpose: Searches the Tor search engine 'Ahmia' for content related to the
+# target.
+#
+# Author: Steve Micallef
+#
+# Created: 20/06/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ahmia(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Ahmia",
+ 'flags': ["tor"],
+ 'summary': "Search Tor 'Ahmia' search engine for mentions of the target.",
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://ahmia.fi/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://ahmia.fi/documentation/",
+ "https://github.com/ahmia/",
+ "http://msydqstlz2kzerdg.onion/",
+ "https://ahmia.fi/stats"
+ ],
+ 'favIcon': "https://ahmia.fi/static/images/favicon.ico",
+ 'logo': "https://ahmia.fi/static/images/ahmiafi_black.png",
+ 'description': "Ahmia searches hidden services on the Tor network. To access these hidden services,"
+ "you need the Tor browser bundle. Abuse material is not allowed on Ahmia. "
+ "See our service blacklist and report abuse material if you find it in the index. "
+ "It will be removed as soon as possible.\n"
+ "Contributors to Ahmia believe that the Tor network is an important and "
+ "resilient distributed platform for anonymity and privacy worldwide. "
+ "By providing a search engine for what many call the \"deep web\" or \"dark net\", "
+ "Ahmia makes hidden services accessible to a wide range of people, not just Tor network early adopters."
+ }
+ }
+
+ # Default options
+ opts = {
+ 'fetchlinks': True,
+ 'fullnames': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target.",
+ 'fullnames': "Search for human names?"
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "HUMAN_NAME", "EMAILADDR"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["DARKNET_MENTION_URL", "DARKNET_MENTION_CONTENT"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if not self.opts['fullnames'] and eventName == 'HUMAN_NAME':
+ self.debug(f"Skipping HUMAN_NAME: {eventData}")
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ params = urllib.parse.urlencode({
+ 'q': eventData
+ })
+
+ data = self.sf.fetchUrl(
+ f"https://ahmia.fi/search/?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=15
+ )
+
+ if not data:
+ self.info(f"No results for {eventData} returned from Ahmia.fi.")
+ return
+
+ content = data.get('content')
+
+ if not content:
+ self.info(f"No results for {eventData} returned from Ahmia.fi.")
+ return
+
+ # We don't bother with pagination as Ahmia seems fairly limited in coverage
+ # and displays hundreds of results per page
+ links = re.findall("redirect_url=(.[^\"]+)\"", content, re.IGNORECASE | re.DOTALL)
+
+ if not links:
+ self.info(f"No results for {eventData} returned from Ahmia.fi.")
+ return
+
+ for link in links:
+ if self.checkForStop():
+ return
+
+ if link in self.results:
+ continue
+
+ self.results[link] = True
+
+ self.debug(f"Found a darknet mention: {link}")
+
+ if not self.sf.urlFQDN(link).endswith(".onion"):
+ continue
+
+ if not self.opts['fetchlinks']:
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ res = self.sf.fetchUrl(
+ link,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False
+ )
+
+ if res['content'] is None:
+ self.debug(f"Ignoring {link} as no data returned")
+ continue
+
+ if eventData not in res['content']:
+ self.debug(f"Ignoring {link} as no mention of {eventData}")
+ continue
+
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)
+ self.notifyListeners(evt)
+
+ try:
+ startIndex = res['content'].index(eventData) - 120
+ endIndex = startIndex + len(eventData) + 240
+ except Exception:
+ self.debug(f"String '{eventData}' not found in content.")
+ continue
+
+ wdata = res['content'][startIndex:endIndex]
+ evt = SpiderFootEvent("DARKNET_MENTION_CONTENT", f"...{wdata}...", self.__name__, evt)
+ self.notifyListeners(evt)
+
+# End of sfp_ahmia class
diff --git a/spiderfoot/modules/sfp_alienvault.py b/spiderfoot/modules/sfp_alienvault.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ef5c712c2ad25ac1f221b05d468f3d20167f8dd
--- /dev/null
+++ b/spiderfoot/modules/sfp_alienvault.py
@@ -0,0 +1,498 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_alienvault
+# Purpose: Query AlienVault OTX
+#
+# Author: Steve Micallef
+#
+# Created: 26/03/2017
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from datetime import datetime
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_alienvault(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AlienVault OTX",
+ 'summary': "Obtain information from AlienVault Open Threat Exchange (OTX)",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://otx.alienvault.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://otx.alienvault.com/faq",
+ "https://otx.alienvault.com/api",
+ "https://otx.alienvault.com/submissions/list",
+ "https://otx.alienvault.com/pulse/create",
+ "https://otx.alienvault.com/endpoint-security/welcome",
+ "https://otx.alienvault.com/browse/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://otx.alienvault.com/",
+ "Sign up for a free account",
+ "Navigate to https://otx.alienvault.com/settings",
+ "The API key is listed under 'OTX Key'"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://otx.alienvault.com/",
+ 'logo': "https://otx.alienvault.com/assets/images/otx-logo.svg",
+ 'description': "The World’s First Truly Open Threat Intelligence Community\n"
+ "Open Threat Exchange is the neighborhood watch of the global intelligence community. "
+ "It enables private companies, independent security researchers, and government agencies to "
+ "openly collaborate and share the latest information about emerging threats, attack methods, "
+ "and malicious actors, promoting greater security across the entire community.\n"
+ "OTX changed the way the intelligence community creates and consumes threat data. "
+ "In OTX, anyone in the security community can contribute, discuss, research, validate, "
+ "and share threat data. You can integrate community-generated OTX threat data directly "
+ "into your AlienVault and third-party security products, so that your threat detection defenses "
+ "are always up to date with the latest threat intelligence. "
+ "Today, 100,000 participants in 140 countries contribute over 19 million threat indicators daily."
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "verify": True,
+ "reputation_age_limit_days": 30,
+ "cohost_age_limit_days": 30,
+ "threat_score_min": 2,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxv6netblock': 120,
+ 'subnetlookup': True,
+ 'maxsubnet': 24,
+ 'maxv6subnet': 120,
+ 'max_pages': 50,
+ 'maxcohost': 100,
+ 'checkaffiliates': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "AlienVault OTX API Key.",
+ "verify": "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ "reputation_age_limit_days": "Ignore any reputation records older than this many days. 0 = unlimited.",
+ "cohost_age_limit_days": "Ignore any co-hosts older than this many days. 0 = unlimited.",
+ "threat_score_min": "Minimum AlienVault threat score.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum IPv4 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6netblock': "If looking up owned netblocks, the maximum IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",
+ 'maxsubnet': "If looking up subnets, the maximum IPv4 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6subnet': "If looking up subnets, the maximum IPv6 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'max_pages': "Maximum number of pages of URL results to fetch.",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ 'checkaffiliates': "Apply checks to affiliates?"
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ "NETBLOCK_OWNER",
+ "NETBLOCKV6_OWNER",
+ "NETBLOCK_MEMBER",
+ "NETBLOCKV6_MEMBER",
+ "NETBLOCK_OWNER",
+ "NETBLOCK_MEMBER",
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ "CO_HOSTED_SITE",
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "LINKED_URL_INTERNAL"
+ ]
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from AlienVault OTX.")
+ return None
+
+ # Future proofing - AlienVault OTX does not implement rate limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by AienVault OTX")
+ self.errorState = True
+ return None
+
+ if res['code'] == "403":
+ self.error("AlienVault OTX API key seems to have been rejected or you have exceeded usage limits for the month.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None or res['code'] == "404":
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from AlienVault OTX: {e}")
+
+ return None
+
+ def queryReputation(self, qry):
+ if ":" in qry:
+ target_type = "IPv6"
+ elif self.sf.validIP(qry):
+ target_type = "IPv4"
+ else:
+ self.info(f"Could not determine target type for {qry}")
+ return None
+
+ headers = {
+ 'Accept': 'application/json',
+ 'X-OTX-API-KEY': self.opts['api_key']
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://otx.alienvault.com/api/v1/indicators/{target_type}/{qry}/reputation",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers)
+
+ return self.parseApiResponse(res)
+
+ def queryPassiveDns(self, qry):
+ if ":" in qry:
+ target_type = "IPv6"
+ elif self.sf.validIP(qry):
+ target_type = "IPv4"
+ else:
+ self.info(f"Could not determine target type for {qry}")
+ return None
+
+ headers = {
+ 'Accept': 'application/json',
+ 'X-OTX-API-KEY': self.opts['api_key']
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://otx.alienvault.com/api/v1/indicators/{target_type}/{qry}/passive_dns",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers)
+
+ return self.parseApiResponse(res)
+
+ def queryDomainUrlList(self, qry, page=1, per_page=50):
+ params = urllib.parse.urlencode({
+ 'page': page,
+ 'limit': per_page
+ })
+
+ headers = {
+ 'Accept': 'application/json',
+ 'X-OTX-API-KEY': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl(
+ f"https://otx.alienvault.com/api/v1/indicators/domain/{qry}/url_list?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers)
+
+ return self.parseApiResponse(res)
+
+ def queryHostnameUrlList(self, qry, page=1, per_page=50):
+ params = urllib.parse.urlencode({
+ 'page': page,
+ 'limit': per_page
+ })
+
+ headers = {
+ 'Accept': 'application/json',
+ 'X-OTX-API-KEY': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl(
+ f"https://otx.alienvault.com/api/v1/indicators/hostname/{qry}/url_list?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers)
+
+ return self.parseApiResponse(res)
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:
+ return
+
+ if eventName == 'INTERNET_NAME':
+ urls = list()
+ page = 1
+ while page <= self.opts['max_pages']:
+ if self.checkForStop():
+ break
+ if self.errorState:
+ break
+
+ data = self.queryHostnameUrlList(eventData, page=page)
+ page += 1
+
+ url_list = data.get('url_list')
+ if not url_list:
+ break
+
+ for url in url_list:
+ u = url.get('url')
+ if not u:
+ continue
+ urls.append(u)
+
+ if not data.get('has_next'):
+ break
+
+ if self.sf.isDomain(eventData, self.opts['_internettlds']):
+ page = 1
+ while page <= self.opts['max_pages']:
+ if self.checkForStop():
+ break
+ if self.errorState:
+ break
+
+ data = self.queryDomainUrlList(eventData, page=page)
+ page += 1
+
+ url_list = data.get('url_list')
+ if not url_list:
+ break
+
+ for url in url_list:
+ u = url.get('url')
+ if not u:
+ continue
+ urls.append(u)
+
+ if not data.get('has_next'):
+ break
+
+ for url in set(urls):
+ if not url:
+ continue
+
+ host = self.sf.urlFQDN(url.lower())
+
+ if not self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ continue
+
+ if url not in self.results:
+ self.results[url] = True
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', url, self.__name__, event)
+ self.notifyListeners(evt)
+
+ return
+
+ if eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts['netblocklookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_OWNER':
+ max_netblock = self.opts['maxv6netblock']
+ else:
+ max_netblock = self.opts['maxnetblock']
+
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ if eventName in ['NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ if not self.opts['subnetlookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_MEMBER':
+ max_subnet = self.opts['maxv6subnet']
+ else:
+ max_subnet = self.opts['maxsubnet']
+
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+
+ # For IP addresses, do the additional passive DNS lookup
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ ret = self.queryPassiveDns(eventData)
+
+ if ret is None:
+ self.info(f"No Passive DNS info for {eventData}")
+ else:
+ passive_dns = ret.get('passive_dns')
+ if passive_dns:
+ self.debug(f"Found passive DNS results for {eventData} in AlienVault OTX")
+ for rec in passive_dns:
+ host = rec.get('hostname')
+
+ if not host:
+ continue
+
+ if self.getTarget().matches(host, includeParents=True):
+ evtType = "INTERNET_NAME"
+ if not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ evtType = "INTERNET_NAME_UNRESOVLED"
+ evt = SpiderFootEvent(evtType, host, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ if self.opts['cohost_age_limit_days'] > 0:
+ try:
+ last = rec.get("last", "")
+ last_dt = datetime.strptime(last, '%Y-%m-%dT%H:%M:%S')
+ last_ts = int(time.mktime(last_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts['cohost_age_limit_days'])
+ if last_ts < age_limit_ts:
+ self.debug(f"Passive DNS record {host} found for {eventData} is too old ({last_dt}), skipping.")
+ continue
+ except Exception:
+ self.info("Could not parse date from AlienVault data, so ignoring cohost_age_limit_days")
+
+ if self.opts["verify"] and not self.sf.validateIP(host, eventData):
+ self.debug(f"Co-host {host} no longer resolves to {eventData}, skipping")
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ e = SpiderFootEvent("CO_HOSTED_SITE", host, self.__name__, event)
+ self.notifyListeners(e)
+ self.cohostcount += 1
+ else:
+ self.info(f"Maximum co-host threshold exceeded ({self.opts['maxcohost']}), ignoring co-host {host}")
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS', 'NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ evtType = 'MALICIOUS_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS', 'NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+ elif eventName == "INTERNET_NAME":
+ evtType = 'MALICIOUS_INTERNET_NAME'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+ if self.errorState:
+ return
+
+ rec = self.queryReputation(addr)
+
+ if not rec:
+ continue
+
+ if rec.get("reputation", None):
+ self.debug(f"Found reputation info for {addr} in AlienVault OTX")
+ rec_history = rec['reputation'].get("activities", list())
+ threat_score = rec['reputation']['threat_score']
+ threat_score_min = self.opts['threat_score_min']
+
+ if threat_score < threat_score_min:
+ self.debug(f"Threat score {threat_score} smaller than {threat_score_min}, skipping.")
+ continue
+
+ descr = f"AlienVault Threat Score: {threat_score}"
+
+ for result in rec_history:
+ nm = result.get("name", None)
+
+ if nm is None or nm in descr:
+ continue
+
+ descr += "\n - " + nm
+ created = result.get("last_date", "")
+ if self.opts['reputation_age_limit_days'] > 0:
+ try:
+ # 2014-11-06T10:45:00.000
+ created_dt = datetime.strptime(created, '%Y-%m-%dT%H:%M:%S')
+ created_ts = int(time.mktime(created_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts['reputation_age_limit_days'])
+ if created_ts < age_limit_ts:
+ self.debug(f"Reputation record found for {addr} is too old ({created_dt}), skipping.")
+ continue
+ except Exception:
+ self.info("Could not parse date from AlienVault data, so ignoring reputation_age_limit_days")
+
+ # For netblocks, we need to create the IP address event so that
+ # the threat intel event is more meaningful.
+ if eventName == 'NETBLOCK_OWNER':
+ pevent = SpiderFootEvent("IP_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ if eventName == 'NETBLOCKV6_OWNER':
+ pevent = SpiderFootEvent("IPV6_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCK_MEMBER':
+ pevent = SpiderFootEvent("AFFILIATE_IPADDR", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCKV6_MEMBER':
+ pevent = SpiderFootEvent("AFFILIATE_IPV6_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ else:
+ pevent = event
+
+ e = SpiderFootEvent(evtType, descr, self.__name__, pevent)
+ self.notifyListeners(e)
+
+# End of sfp_alienvault class
diff --git a/spiderfoot/modules/sfp_alienvaultiprep.py b/spiderfoot/modules/sfp_alienvaultiprep.py
new file mode 100644
index 0000000000000000000000000000000000000000..375a8fce93ac97ba69bb107079d55b4e7142f7b0
--- /dev/null
+++ b/spiderfoot/modules/sfp_alienvaultiprep.py
@@ -0,0 +1,215 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_alienvaultiprep
+# Purpose: Check if an IP or netblock is malicious according to the AlienVault
+# IP Reputation database.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_alienvaultiprep(SpiderFootPlugin):
+
+ meta = {
+ 'name': "AlienVault IP Reputation",
+ 'summary': "Check if an IP or netblock is malicious according to the AlienVault IP Reputation database.",
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://cybersecurity.att.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://cybersecurity.att.com/documentation/",
+ "https://cybersecurity.att.com/resource-center",
+ "https://success.alienvault.com/s/article/Can-I-use-the-OTX-IP-Reputation-List-as-a-blocklist",
+ ],
+ 'favIcon': "https://cdn-cybersecurity.att.com/images/uploads/logos/att-globe.svg",
+ 'logo': "https://cdn-cybersecurity.att.com/images/uploads/logos/att-business-web.svg",
+ 'description': "Looking at security through new eyes.\n"
+ "AT&T Business and AlienVault have joined forces to create AT&T Cybersecurity, "
+ "with a vision to bring together the people, process, and technology "
+ "that help businesses of any size stay ahead of threats.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "NETBLOCK_MEMBER",
+ "NETBLOCK_OWNER"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_NETBLOCK",
+ ]
+
+ def queryBlacklist(self, target, targetType):
+ blacklist = self.retrieveBlacklist()
+
+ if not blacklist:
+ return False
+
+ if targetType == "ip":
+ if target in blacklist:
+ self.debug(f"IP address {target} found in AlienVault IP Reputation Database blacklist.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in blacklist:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in AlienVault IP Reputation Database blacklist.")
+ return True
+
+ return False
+
+ def retrieveBlacklist(self):
+ blacklist = self.sf.cacheGet('alienvaultiprep', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://reputation.alienvault.com/reputation.generic",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from AlienVault IP Reputation Database.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from AlienVault IP Reputation Database")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("alienvaultiprep", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from AlienVault IP Reputation Database
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ if not blacklist:
+ return ips
+
+ for ip in blacklist.split('\n'):
+ ip = ip.strip().split(" #")[0]
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with AlienVault IP Reputation Database")
+
+ if not self.queryBlacklist(eventData, targetType):
+ return
+
+ url = "https://reputation.alienvault.com/reputation.generic"
+ text = f"AlienVault IP Reputation Database [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_alienvaultiprep class
diff --git a/spiderfoot/modules/sfp_apple_itunes.py b/spiderfoot/modules/sfp_apple_itunes.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3ca9e3c69d31153a6c81a9a4433a99553592a57
--- /dev/null
+++ b/spiderfoot/modules/sfp_apple_itunes.py
@@ -0,0 +1,203 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_apple_itunes
+# Purpose: Query Apple iTunes for mobile apps.
+#
+# Author:
+#
+# Created: 2020-09-19
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_apple_itunes(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Apple iTunes",
+ 'summary': "Search Apple iTunes for mobile apps.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://itunes.apple.com/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'favIcon': "https://itunes.apple.com/favicon.ico",
+ 'logo': "https://itunes.apple.com/favicon.ico",
+ 'description': "The Apple iTunes store is a store for downloading "
+ "and purchasing apps for Apple devices.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'DOMAIN_NAME'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'APPSTORE_ENTRY',
+ 'INTERNET_NAME',
+ 'LINKED_URL_INTERNAL',
+ 'AFFILIATE_INTERNET_NAME',
+ 'RAW_RIR_DATA'
+ ]
+
+ def query(self, qry, limit=100):
+ params = urllib.parse.urlencode({
+ 'media': 'software',
+ 'entity': 'software,iPadSoftware,softwareDeveloper',
+ 'limit': limit,
+ 'term': qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://itunes.apple.com/search?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from Apple iTunes: {e}")
+ return None
+
+ results = data.get('results')
+
+ if not results:
+ self.debug(f"No results found for {qry}")
+ return None
+
+ return results
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if eventName not in self.watchedEvents():
+ return
+
+ self.results[eventData] = True
+
+ domain_reversed = '.'.join(list(reversed(eventData.lower().split('.'))))
+ data = self.query(domain_reversed)
+
+ if not data:
+ self.info(f"No results found for {eventData}")
+ return
+
+ urls = list()
+ hosts = list()
+ found = False
+
+ for result in data:
+ bundleId = result.get('bundleId')
+
+ if not bundleId:
+ continue
+
+ trackName = result.get('trackName')
+
+ if not trackName:
+ continue
+
+ version = result.get('version')
+
+ if not version:
+ continue
+
+ app_full_name = f"{trackName} {version} ({bundleId})"
+
+ if (
+ domain_reversed != bundleId.lower()
+ and not bundleId.lower().startswith(f"{domain_reversed}.")
+ and not bundleId.lower().endswith(f".{domain_reversed}")
+ and f".{domain_reversed}." not in bundleId.lower()
+ ):
+ self.debug(f"App {app_full_name} does not match {domain_reversed}, skipping")
+ continue
+
+ trackViewUrl = result.get('trackViewUrl')
+
+ if not trackViewUrl:
+ continue
+
+ app_data = f"{app_full_name}\n{trackViewUrl} "
+
+ evt = SpiderFootEvent('APPSTORE_ENTRY', app_data, self.__name__, event)
+ self.notifyListeners(evt)
+ found = True
+
+ sellerUrl = result.get('sellerUrl')
+
+ if not sellerUrl:
+ continue
+
+ urls.append(sellerUrl)
+
+ for url in set(urls):
+ host = self.sf.urlFQDN(url)
+
+ if not host:
+ continue
+
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', url, self.__name__, event)
+ self.notifyListeners(evt)
+ found = True
+
+ hosts.append(host)
+
+ for host in set(hosts):
+ if not host:
+ continue
+
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt = SpiderFootEvent('INTERNET_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent('AFFILIATE_INTERNET_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ evt = SpiderFootEvent('RAW_RIR_DATA', json.dumps(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_apple_itunes class
diff --git a/spiderfoot/modules/sfp_archiveorg.py b/spiderfoot/modules/sfp_archiveorg.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae744ba53cff2a87f64e04f935d54930247c93b5
--- /dev/null
+++ b/spiderfoot/modules/sfp_archiveorg.py
@@ -0,0 +1,187 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_archiveorg
+# Purpose: Queries archive.org (Wayback machine) for historic versions of
+# certain pages.
+#
+# Author: Steve Micallef
+#
+# Created: 20/07/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import datetime
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_archiveorg(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Archive.org",
+ 'summary': "Identifies historic versions of interesting files/pages from the Wayback Machine.",
+ 'flags': ["slow"],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://archive.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://archive.org/projects/",
+ "https://archive.org/services/docs/api/"
+ ],
+ 'favIcon': "https://archive.org/images/glogo.jpg",
+ 'logo': "https://archive.org/images/glogo.jpg",
+ 'description': "Internet Archive is a non-profit library of millions of free books, movies, software, music, websites, and more.\n"
+ "The Internet Archive, a 501(c)(3) non-profit, is building a digital library of Internet sites "
+ "and other cultural artifacts in digital form. Like a paper library, we provide free access to "
+ "researchers, historians, scholars, the print disabled, and the general public. "
+ "Our mission is to provide Universal Access to All Knowledge.\n"
+ "We began in 1996 by archiving the Internet itself, a medium that was just beginning to grow in use. "
+ "Like newspapers, the content published on the web was ephemeral - but unlike newspapers, no one was saving it. "
+ "Today we have 20+ years of web history accessible through the Wayback Machine and we work with 625+ library and "
+ "other partners through our Archive-It program to identify important web pages.",
+ }
+
+ }
+
+ # Default options
+ opts = {
+ 'farback': "30,60,90",
+ 'intfiles': True,
+ 'passwordpages': True,
+ 'formpages': False,
+ 'flashpages': False,
+ 'javapages': False,
+ 'staticpages': False,
+ 'uploadpages': False,
+ 'webframeworkpages': False,
+ 'javascriptpages': False
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'farback': "Number of days back to look for older versions of files/pages in the Wayback Machine snapshots. Comma-separate the values, so for example 30,60,90 means to look for snapshots 30 days, 60 days and 90 days back.",
+ 'intfiles': "Query the Wayback Machine for historic versions of Interesting Files.",
+ 'passwordpages': "Query the Wayback Machine for historic versions of URLs with passwords.",
+ 'formpages': "Query the Wayback Machine for historic versions of URLs with forms.",
+ 'uploadpages': "Query the Wayback Machine for historic versions of URLs accepting uploads.",
+ 'flashpages': "Query the Wayback Machine for historic versions of URLs containing Flash.",
+ 'javapages': "Query the Wayback Machine for historic versions of URLs using Java Applets.",
+ 'staticpages': "Query the Wayback Machine for historic versions of purely static URLs.",
+ "webframeworkpages": "Query the Wayback Machine for historic versions of URLs using Javascript frameworks.",
+ "javascriptpages": "Query the Wayback Machine for historic versions of URLs using Javascript."
+ }
+
+ results = None
+ foundDates = list()
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.foundDates = list()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERESTING_FILE", "URL_PASSWORD", "URL_FORM", "URL_FLASH",
+ "URL_STATIC", "URL_JAVA_APPLET", "URL_UPLOAD", "URL_JAVASCRIPT",
+ "URL_WEB_FRAMEWORK"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["INTERESTING_FILE_HISTORIC", "URL_PASSWORD_HISTORIC",
+ "URL_FORM_HISTORIC", "URL_FLASH_HISTORIC",
+ "URL_STATIC_HISTORIC", "URL_JAVA_APPLET_HISTORIC",
+ "URL_UPLOAD_HISTORIC", "URL_WEB_FRAMEWORK_HISTORIC",
+ "URL_JAVASCRIPT_HISTORIC"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName == "INTERESTING_FILE" and not self.opts['intfiles']:
+ return
+ if eventName == "URL_PASSWORD" and not self.opts['passwordpages']:
+ return
+ if eventName == "URL_STATIC" and not self.opts['staticpages']:
+ return
+ if eventName == "URL_FORM" and not self.opts['formpages']:
+ return
+ if eventName == "URL_UPLOAD" and not self.opts['uploadpages']:
+ return
+ if eventName == "URL_JAVA_APPLET" and not self.opts['javapages']:
+ return
+ if eventName == "URL_FLASH" and not self.opts['flashpages']:
+ return
+ if eventName == "URL_JAVASCRIPT" and not self.opts['javascriptpages']:
+ return
+ if eventName == "URL_WEB_FRAMEWORK" and not self.opts['webframeworkpages']:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ for daysback in self.opts['farback'].split(","):
+ try:
+ newDate = datetime.datetime.now() - datetime.timedelta(days=int(daysback))
+ except Exception:
+ self.error("Unable to parse option for number of days back to search.")
+ self.errorState = True
+ return
+
+ maxDate = newDate.strftime("%Y%m%d")
+
+ url = "https://archive.org/wayback/available?url=" + eventData + \
+ "×tamp=" + maxDate
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ continue
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from Archive.org: {e}")
+ ret = None
+
+ if not ret:
+ self.debug(f"Empty response from archive.org for {eventData}")
+ continue
+
+ if len(ret['archived_snapshots']) < 1:
+ self.debug("No archived snapshots for " + eventData)
+ continue
+
+ wbmlink = ret['archived_snapshots']['closest']['url']
+ if wbmlink in self.foundDates:
+ self.debug("Snapshot already fetched.")
+ continue
+
+ self.foundDates.append(wbmlink)
+ name = eventName + "_HISTORIC"
+
+ self.info("Found a historic file: " + wbmlink)
+ evt = SpiderFootEvent(name, wbmlink, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_archiveorg class
diff --git a/spiderfoot/modules/sfp_arin.py b/spiderfoot/modules/sfp_arin.py
new file mode 100644
index 0000000000000000000000000000000000000000..b97e121f877011c7efa821aec75a98bd801541db
--- /dev/null
+++ b/spiderfoot/modules/sfp_arin.py
@@ -0,0 +1,181 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_arin
+# Purpose: Queries the ARIN internet registry to get netblocks and other
+# bits of info.
+#
+# Author: Steve Micallef
+#
+# Created: 23/02/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_arin(SpiderFootPlugin):
+
+ meta = {
+ 'name': "ARIN",
+ 'summary': "Queries ARIN registry for contact information.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Public Registries"],
+ 'dataSource': {
+ 'website': "https://www.arin.net/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.arin.net/resources/",
+ "https://www.arin.net/reference/",
+ "https://www.arin.net/participate/",
+ "https://www.arin.net/resources/guide/request/",
+ "https://www.arin.net/resources/registry/transfers/",
+ "https://www.arin.net/resources/guide/ipv6/"
+ ],
+ 'favIcon': "https://www.arin.net/img/favicon.ico",
+ 'logo': "https://www.arin.net/img/logo-stnd.svg",
+ 'description': "ARIN is a nonprofit, member-based organization that administers IP addresses & "
+ "ASNs in support of the operation and growth of the Internet.\n"
+ "Established in December 1997 as a Regional Internet Registry, "
+ "the American Registry for Internet Numbers (ARIN) is responsible for the management "
+ "and distribution of Internet number resources such as Internet Protocol (IP) addresses "
+ "and Autonomous System Numbers (ASNs). ARIN manages these resources within its service region, "
+ "which is comprised of Canada, the United States, and many Caribbean and North Atlantic islands.",
+ }
+ }
+
+ # Default options
+ opts = {}
+ optdescs = {}
+
+ results = None
+ currentEventSrc = None
+ keywords = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.currentEventSrc = None
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['DOMAIN_NAME', 'HUMAN_NAME']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "HUMAN_NAME"]
+
+ # Fetch content and notify of the raw data
+ def fetchRir(self, url):
+ head = {"Accept": "application/json"}
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'], headers=head)
+ if res['content'] is not None and res['code'] != "404":
+ return res
+ return None
+
+ # Owner information about an AS
+ def query(self, qtype, value):
+ url = "https://whois.arin.net/rest/"
+
+ if qtype == "domain":
+ url += "pocs;domain=@" + value
+
+ try:
+ if qtype == "name":
+ fname, lname = value.split(" ", 1)
+ if fname.endswith(","):
+ t = fname
+ fname = lname
+ lname = t
+ url += "pocs;first=" + fname + ";last=" + lname
+ except Exception as e:
+ self.debug("Couldn't process name: " + value + " (" + str(e) + ")")
+ return None
+
+ if qtype == "contact":
+ url = value
+
+ res = self.fetchRir(url)
+ if not res:
+ self.debug("No info found/available for " + value + " at ARIN.")
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, self.currentEventSrc)
+ self.notifyListeners(evt)
+ return data
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ self.currentEventSrc = event
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "DOMAIN_NAME":
+ ret = self.query("domain", eventData)
+ if not ret:
+ return
+ if "pocs" in ret:
+ if "pocRef" in ret['pocs']:
+ ref = list()
+ # Might be a list or a dictionary
+ if type(ret['pocs']['pocRef']) == dict:
+ ref = [ret['pocs']['pocRef']]
+ else:
+ ref = ret['pocs']['pocRef']
+ for p in ref:
+ name = p['@name']
+ if "," in name:
+ sname = name.split(", ", 1)
+ name = sname[1] + " " + sname[0]
+
+ evt = SpiderFootEvent("HUMAN_NAME", name,
+ self.__name__, self.currentEventSrc)
+ self.notifyListeners(evt)
+
+ # We just want the raw data so we can get potential
+ # e-mail addresses.
+ self.query("contact", p['$'])
+
+ if eventName == "HUMAN_NAME":
+ ret = self.query("name", eventData)
+ if not ret:
+ return
+ if "pocs" in ret:
+ if "pocRef" in ret['pocs']:
+ ref = list()
+ # Might be a list or a dictionary
+ if type(ret['pocs']['pocRef']) == dict:
+ ref = [ret['pocs']['pocRef']]
+ else:
+ ref = ret['pocs']['pocRef']
+ for p in ref:
+ # We just want the raw data so we can get potential
+ # e-mail addresses.
+ self.query("contact", p['$'])
+
+# End of sfp_arin class
diff --git a/spiderfoot/modules/sfp_azureblobstorage.py b/spiderfoot/modules/sfp_azureblobstorage.py
new file mode 100644
index 0000000000000000000000000000000000000000..daa1a00d26731c2727c4be37361e9a2fa02ac90a
--- /dev/null
+++ b/spiderfoot/modules/sfp_azureblobstorage.py
@@ -0,0 +1,176 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_azureblobstorage
+# Purpose: SpiderFoot plug-in for identifying potential Azure blobs related
+# to the target.
+#
+# Author: Steve Micallef
+#
+# Created: 14/07/2019
+# Copyright: (c) Steve Micallef 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import random
+import threading
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_azureblobstorage(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Azure Blob Finder",
+ 'summary': "Search for potential Azure blobs associated with the target and attempt to list their contents.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Crawling and Scanning"],
+ 'dataSource': {
+ 'website': "https://azure.microsoft.com/en-in/services/storage/blobs/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'favIcon': 'https://azurecomcdn.azureedge.net/cvt-4fd6fa9ffb60246fd6387e4b34f89dc454cdf3df85d2b5d3215846066fceb0b6/images/icon/favicon.ico',
+ 'logo': 'https://azurecomcdn.azureedge.net/cvt-4fd6fa9ffb60246fd6387e4b34f89dc454cdf3df85d2b5d3215846066fceb0b6/images/icon/favicon.ico',
+ 'description': "Massively scalable and secure object storage for cloud-native workloads,"
+ "archives, data lakes, high-performance computing and machine learning."
+ }
+ }
+
+ # Default options
+ opts = {
+ "suffixes": "test,dev,web,beta,bucket,space,files,content,data,prod,staging,production,stage,app,media,development,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data,-prod,-staging,-production,-stage,-app,-media,-development",
+ "_maxthreads": 20
+ }
+
+ # Option descriptions
+ optdescs = {
+ "suffixes": "List of suffixes to append to domains tried as blob storage names",
+ "_maxthreads": "Maximum threads"
+ }
+
+ results = None
+ s3results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.s3results = self.tempStorage()
+ self.results = self.tempStorage()
+ self.lock = threading.Lock()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["CLOUD_STORAGE_BUCKET"]
+
+ def checkSite(self, url):
+ res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot", noLog=True)
+
+ if res['code']:
+ with self.lock:
+ self.s3results[url] = True
+
+ def threadSites(self, siteList):
+ self.s3results = dict()
+ running = True
+ i = 0
+ t = []
+
+ for site in siteList:
+ if self.checkForStop():
+ return None
+
+ self.info("Spawning thread to check bucket: " + site)
+ tname = str(random.SystemRandom().randint(0, 999999999))
+ t.append(threading.Thread(name='thread_sfp_azureblobstorages_' + tname,
+ target=self.checkSite, args=(site,)))
+ t[i].start()
+ i += 1
+
+ # Block until all threads are finished
+ while running:
+ found = False
+ for rt in threading.enumerate():
+ if rt.name.startswith("thread_sfp_azureblobstorages_"):
+ found = True
+
+ if not found:
+ running = False
+
+ time.sleep(0.25)
+
+ # Return once the scanning has completed
+ return self.s3results
+
+ def batchSites(self, sites):
+ i = 0
+ res = list()
+ siteList = list()
+
+ for site in sites:
+ if i >= self.opts['_maxthreads']:
+ data = self.threadSites(siteList)
+ if data is None:
+ return res
+
+ for ret in list(data.keys()):
+ if data[ret]:
+ res.append(ret)
+ i = 0
+ siteList = list()
+
+ siteList.append(site)
+ i += 1
+
+ return res
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName == "LINKED_URL_EXTERNAL":
+ if ".blob.core.windows.net" in eventData:
+ b = self.sf.urlFQDN(eventData)
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", b, self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ targets = [eventData.replace('.', '')]
+ kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ if kw:
+ targets.append(kw)
+
+ urls = list()
+ for t in targets:
+ suffixes = [''] + self.opts['suffixes'].split(',')
+ for s in suffixes:
+ if self.checkForStop():
+ return
+
+ b = t + s + ".blob.core.windows.net"
+ url = "https://" + b
+ urls.append(url)
+
+ # Batch the scans
+ ret = self.batchSites(urls)
+ for b in ret:
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", b, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_azureblobstorage class
diff --git a/spiderfoot/modules/sfp_base64.py b/spiderfoot/modules/sfp_base64.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac45a4f050749d5ad43784cdbc1bcc0894ae0328
--- /dev/null
+++ b/spiderfoot/modules/sfp_base64.py
@@ -0,0 +1,97 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_base64
+# Purpose: Identifies (best-effort) Base64-encoded strings in URLs.
+#
+# Author: Steve Micallef
+#
+# Created: 31/01/2017
+# Copyright: (c) Steve Micallef 2017
+# -------------------------------------------------------------------------------
+
+import base64
+import re
+import urllib.parse
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_base64(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Base64 Decoder",
+ 'summary': "Identify Base64-encoded strings in URLs, often revealing interesting hidden information.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ 'minlength': 10
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'minlength': "The minimum length a string that looks like a base64-encoded string needs to be."
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["BASE64_DATA"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ decoded_data = urllib.parse.unquote(eventData)
+
+ # Note: this will miss base64 encoded strings with no padding
+ # (strings which do not end with '=' or '==')
+ pat = re.compile(r"([A-Za-z0-9+\/]+={1,2})")
+ m = re.findall(pat, decoded_data)
+ for match in m:
+ if self.checkForStop():
+ return
+
+ minlen = int(self.opts['minlength'])
+ if len(match) < minlen:
+ continue
+
+ # Base64-encoded strings don't look like normal strings
+ caps = sum(1 for c in match if c.isupper())
+ if caps < (minlen / 4):
+ continue
+
+ if isinstance(match, str):
+ string = match
+ else:
+ string = str(match)
+
+ self.info(f"Found Base64 string: {match}")
+
+ try:
+ string += f" ({base64.b64decode(match).decode('utf-8')})"
+ except Exception as e:
+ self.debug(f"Unable to base64-decode string: {e}")
+ continue
+
+ evt = SpiderFootEvent("BASE64_DATA", string, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_base64 class
diff --git a/spiderfoot/modules/sfp_bgpview.py b/spiderfoot/modules/sfp_bgpview.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f1a318ec2f91f4ddcc683d3f01514aceea01d18
--- /dev/null
+++ b/spiderfoot/modules/sfp_bgpview.py
@@ -0,0 +1,249 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bgpview
+# Purpose: Query BGPView API - https://bgpview.docs.apiary.io/
+#
+# Author:
+#
+# Created: 2019-09-03
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bgpview(SpiderFootPlugin):
+
+ meta = {
+ 'name': "BGPView",
+ 'summary': "Obtain network information from BGPView API.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://bgpview.io/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://bgpview.docs.apiary.io/#",
+ "https://bgpview.docs.apiary.io/api-description-document"
+ ],
+ 'favIcon': "https://bgpview.io/favicon-32x32.png",
+ 'logo': "https://bgpview.io/assets/logo.png",
+ 'description': "BGPView is a simple API allowing consumers to view all sort of analytics data about the current state and structure of the internet.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'IPV6_ADDRESS',
+ 'BGP_AS_MEMBER',
+ 'NETBLOCK_MEMBER',
+ 'NETBLOCKV6_MEMBER'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'BGP_AS_MEMBER',
+ 'NETBLOCK_MEMBER',
+ 'NETBLOCKV6_MEMBER',
+ 'PHYSICAL_ADDRESS',
+ 'RAW_RIR_DATA'
+ ]
+
+ def queryAsn(self, qry):
+ res = self.sf.fetchUrl("https://api.bgpview.io/asn/" + qry.replace('AS', ''),
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ json_data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from BGPView: {e}")
+ return None
+
+ if json_data.get('status') != 'ok':
+ self.debug("No results found for ASN " + qry)
+ return None
+
+ data = json_data.get('data')
+
+ if not data:
+ self.debug("No results found for ASN " + qry)
+ return None
+
+ return data
+
+ def queryIp(self, qry):
+ res = self.sf.fetchUrl("https://api.bgpview.io/ip/" + qry,
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ json_data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from BGPView: {e}")
+ return None
+
+ if json_data.get('status') != 'ok':
+ self.debug("No results found for IP address " + qry)
+ return None
+
+ data = json_data.get('data')
+
+ if not data:
+ self.debug("No results found for IP address " + qry)
+ return None
+
+ return data
+
+ def queryNetblock(self, qry):
+ res = self.sf.fetchUrl("https://api.bgpview.io/prefix/" + qry,
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ json_data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from BGPView: {e}")
+ return None
+
+ if json_data.get('status') != 'ok':
+ self.debug("No results found for netblock " + qry)
+ return None
+
+ data = json_data.get('data')
+
+ if not data:
+ self.debug("No results found for netblock " + qry)
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'BGP_AS_MEMBER':
+ data = self.queryAsn(eventData)
+
+ if not data:
+ self.info("No results found for ASN " + eventData)
+ return
+
+ e = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ address = data.get('owner_address')
+
+ if not address:
+ return
+
+ evt = SpiderFootEvent('PHYSICAL_ADDRESS', ', '.join([_f for _f in address if _f]), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName in ['NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ data = self.queryNetblock(eventData)
+
+ if not data:
+ self.info("No results found for netblock " + eventData)
+ return
+
+ e = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ address = data.get('owner_address')
+
+ if not address:
+ return
+
+ evt = SpiderFootEvent('PHYSICAL_ADDRESS', ', '.join([_f for _f in address if _f]), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ data = self.queryIp(eventData)
+
+ if not data:
+ self.info("No results found for IP address " + eventData)
+ return
+
+ e = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ prefixes = data.get('prefixes')
+
+ if not prefixes:
+ self.info("No prefixes found for IP address " + eventData)
+ return
+
+ for prefix in prefixes:
+ p = prefix.get('prefix')
+ if not p:
+ continue
+
+ if not prefix.get('asn'):
+ continue
+
+ asn = prefix.get('asn').get('asn')
+ if not asn:
+ continue
+
+ self.info(f"Netblock found: {p} ({asn})")
+ evt = SpiderFootEvent("BGP_AS_MEMBER", str(asn), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.validIpNetwork(p):
+ if ":" in p:
+ evt = SpiderFootEvent("NETBLOCKV6_MEMBER", p, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("NETBLOCK_MEMBER", p, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_bgpview class
diff --git a/spiderfoot/modules/sfp_binaryedge.py b/spiderfoot/modules/sfp_binaryedge.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ca728f65aefaf551a6ddeacb0e32d0e420723a6
--- /dev/null
+++ b/spiderfoot/modules/sfp_binaryedge.py
@@ -0,0 +1,457 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_binaryedge
+# Purpose: Query binaryedge.io using their API
+#
+# Author: Steve Micallef
+#
+# Created: 02/04/2019
+# Copyright: (c) Steve Micallef 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_binaryedge(SpiderFootPlugin):
+
+ meta = {
+ 'name': "BinaryEdge",
+ 'summary': "Obtain information from BinaryEdge.io Internet scanning systems, including breaches, vulnerabilities, torrents and passive DNS.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://www.binaryedge.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.binaryedge.io/",
+ "https://www.binaryedge.io/data.html"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.binaryedge.io/pricing.html",
+ "Select a plan",
+ "Sign up with new account",
+ "Go to Account",
+ "The API key is listed under 'API Access'"
+ ],
+ 'favIcon': "https://www.binaryedge.io/img/favicon/favicon-32x32.png",
+ 'logo': "https://www.binaryedge.io/img/logo.png",
+ 'description': "We scan the entire public internet, create real-time threat intelligence streams, "
+ "and reports that show the exposure of what is connected to the Internet.\n"
+ "We have built a distributed platform of scanners and honeypots, to acquire, classify and correlate different types of data.\n"
+ "We use all of these datapoints to match those digital assets to an organization, "
+ "allowing us to provide a global, up-to-date, view of organizations known and unknown assets.",
+ }
+ }
+
+ opts = {
+ 'binaryedge_api_key': "",
+ 'torrent_age_limit_days': 30,
+ 'cve_age_limit_days': 30,
+ 'port_age_limit_days': 90,
+ 'maxpages': 10,
+ 'verify': True,
+ 'netblocklookup': False,
+ 'maxnetblock': 24,
+ 'subnetlookup': False,
+ 'maxsubnet': 24,
+ 'maxcohost': 100
+ }
+
+ optdescs = {
+ 'binaryedge_api_key': "BinaryEdge.io API Key.",
+ 'torrent_age_limit_days': "Ignore any torrent records older than this many days. 0 = unlimited.",
+ 'cve_age_limit_days': "Ignore any vulnerability records older than this many days. 0 = unlimited.",
+ 'port_age_limit_days': "Ignore any discovered open ports/banners older than this many days. 0 = unlimited.",
+ 'verify': 'Verify that any hostnames found on the target domain still resolve?',
+ 'maxpages': "Maximum number of pages to iterate through, to avoid exceeding BinaryEdge API usage limits. APIv2 has a maximum of 500 pages (10,000 results).",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting."
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+ reportedhosts = None
+ checkedips = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.reportedhosts = self.tempStorage()
+ self.checkedips = self.tempStorage()
+ self.cohostcount = 0
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "DOMAIN_NAME",
+ "EMAILADDR",
+ "NETBLOCK_OWNER",
+ "NETBLOCK_MEMBER"
+ ]
+
+ def producedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "DOMAIN_NAME",
+ "VULNERABILITY_CVE_CRITICAL",
+ "VULNERABILITY_CVE_HIGH",
+ "VULNERABILITY_CVE_MEDIUM",
+ "VULNERABILITY_CVE_LOW",
+ "VULNERABILITY_GENERAL",
+ "TCP_PORT_OPEN",
+ "TCP_PORT_OPEN_BANNER",
+ "EMAILADDR_COMPROMISED",
+ "UDP_PORT_OPEN",
+ "UDP_PORT_OPEN_INFO",
+ "CO_HOSTED_SITE",
+ "MALICIOUS_IPADDR"
+ ]
+
+ def query(self, qry, querytype, page=1):
+ retarr = list()
+
+ if self.errorState:
+ return None
+
+ if querytype == "email":
+ queryurl = "dataleaks/email"
+ elif querytype == "ip":
+ queryurl = "ip"
+ elif querytype == "torrent":
+ queryurl = "torrent/historical"
+ elif querytype == "vuln":
+ queryurl = "cve/ip"
+ elif querytype == "subs":
+ queryurl = "domains/subdomain"
+ elif querytype == "passive":
+ queryurl = "domains/ip"
+ else:
+ self.error(f"Invalid query type: {querytype}")
+ return None
+
+ headers = {
+ 'X-Key': self.opts['binaryedge_api_key']
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.binaryedge.io/v2/query/{queryurl}/{qry}?page={page}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ if res['code'] in ["429", "500"]:
+ self.error("BinaryEdge.io API key seems to have been rejected or you have exceeded usage limits for the month.")
+ self.errorState = True
+ return None
+
+ if not res['content']:
+ self.info(f"No BinaryEdge.io info found for {qry}")
+ return None
+
+ try:
+ info = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from BinaryEdge.io: {e}")
+ return None
+
+ if info.get('page') and info['total'] > info.get('pagesize', 100) * info.get('page', 0):
+ page = info['page'] + 1
+ if page > self.opts['maxpages']:
+ self.error("Maximum number of pages reached.")
+ return [info]
+ retarr.append(info)
+ e = self.query(qry, querytype, page)
+ if e:
+ retarr.extend(e)
+ else:
+ retarr.append(info)
+
+ return retarr
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["binaryedge_api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "EMAILADDR":
+ ret = self.query(eventData, "email")
+ if ret is None:
+ self.info(f"No leak info for {eventData}")
+ return
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ self.debug("Found compromised account results in BinaryEdge.io")
+
+ for leak in events:
+ e = SpiderFootEvent('EMAILADDR_COMPROMISED', f"{eventData} [{leak}]", self.__name__, event)
+ self.notifyListeners(e)
+
+ # No further API endpoints available for email addresses. we can bail out here
+ return
+
+ if eventName == 'NETBLOCK_OWNER':
+ if not self.opts['netblocklookup']:
+ return
+
+ net_size = IPNetwork(eventData).prefixlen
+ max_netblock = self.opts['maxnetblock']
+ if net_size < max_netblock:
+ self.debug(f"Network size bigger than permitted: {net_size} > {max_netblock}")
+ return
+
+ if eventName == 'NETBLOCK_MEMBER':
+ if not self.opts['subnetlookup']:
+ return
+
+ net_size = IPNetwork(eventData).prefixlen
+ max_subnet = self.opts['maxsubnet']
+ if net_size < max_subnet:
+ self.debug(f"Network size bigger than permitted: {net_size} > {max_subnet}")
+ return
+
+ # For IP Addresses, do the additional passive DNS lookup
+ if eventName == "IP_ADDRESS":
+ evtType = "CO_HOSTED_SITE"
+ ret = self.query(eventData, "passive")
+ if ret is None:
+ self.info(f"No Passive DNS info for {eventData}")
+ return
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ self.debug("Found passive DNS results in BinaryEdge.io")
+ for rec in events:
+ host = rec['domain']
+ if host == eventData:
+ continue
+
+ if self.getTarget().matches(host, includeParents=True):
+ if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ continue
+
+ evt = SpiderFootEvent("INTERNET_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+ if self.sf.isDomain(host, self.opts['_internettlds']):
+ evt = SpiderFootEvent("DOMAIN_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ self.reportedhosts[host] = True
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ e = SpiderFootEvent(evtType, host, self.__name__, event)
+ self.notifyListeners(e)
+ self.cohostcount += 1
+
+ if eventName == "DOMAIN_NAME":
+ ret = self.query(eventData, "subs")
+ if ret is None:
+ self.info(f"No hosts found for {eventData}")
+ return
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ self.debug("Found host results in BinaryEdge.io")
+ for rec in events:
+ if rec in self.reportedhosts:
+ continue
+
+ self.reportedhosts[rec] = True
+
+ if self.opts['verify'] and not self.sf.resolveHost(rec) and not self.sf.resolveHost6(rec):
+ self.debug(f"Couldn't resolve {rec}, so skipping.")
+ continue
+
+ e = SpiderFootEvent('INTERNET_NAME', rec, self.__name__, event)
+ self.notifyListeners(e)
+
+ # Loop through all IP addresses / host names
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ if addr in self.checkedips:
+ continue
+
+ ret = self.query(addr, "torrent")
+ if ret is None:
+ self.info(f"No torrent info for {addr}")
+ continue
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ self.debug(f"Found torrent results for {addr} in BinaryEdge.io")
+
+ for rec in events:
+ created_ts = rec['origin'].get('ts') / 1000
+ age_limit_ts = int(time.time()) - (86400 * self.opts['torrent_age_limit_days'])
+
+ if self.opts['torrent_age_limit_days'] > 0 and created_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ continue
+
+ dat = "Torrent: " + rec.get("torrent", "???").get("name") + " @ " + rec.get('torrent').get("source", "???")
+ e = SpiderFootEvent('MALICIOUS_IPADDR', dat, self.__name__, event)
+ self.notifyListeners(e)
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ if addr in self.checkedips:
+ continue
+
+ ret = self.query(addr, "vuln")
+ if ret is None:
+ self.info(f"No vulnerability info for {addr}")
+ continue
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ results = events.get('results')
+ if not results:
+ continue
+
+ self.debug("Found vulnerability results in BinaryEdge.io")
+ for rec in results:
+ created_ts = rec.get('ts') / 1000
+ age_limit_ts = int(time.time()) - (86400 * self.opts['cve_age_limit_days'])
+
+ if self.opts['cve_age_limit_days'] > 0 and created_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ continue
+
+ cves = rec.get('cves')
+ if cves:
+ for c in cves:
+ etype, cvetext = self.sf.cveInfo(c['cve'])
+ e = SpiderFootEvent(etype, cvetext, self.__name__, event)
+ self.notifyListeners(e)
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ if addr in self.checkedips:
+ continue
+
+ ret = self.query(addr, "ip")
+ if ret is None:
+ self.info(f"No port/banner info for {addr}")
+ return
+
+ for rec in ret:
+ events = rec.get('events')
+ if not events:
+ continue
+
+ self.debug("Found port/banner results in BinaryEdge.io")
+
+ ports = list()
+ for res in events:
+ for prec in res['results']:
+ created_ts = prec['origin'].get('ts') / 1000
+ age_limit_ts = int(time.time()) - (86400 * self.opts['port_age_limit_days'])
+
+ if self.opts['port_age_limit_days'] > 0 and created_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ continue
+
+ port = str(prec['target']['port'])
+ entity = prec['target']['ip'] + ":" + port
+ evttype = "TCP_PORT_OPEN"
+ evtbtype = "TCP_PORT_OPEN_BANNER"
+
+ if prec['target']['protocol'] == "udp":
+ evttype = "UDP_PORT_OPEN"
+ evtbtype = "UDP_PORT_OPEN_INFO"
+
+ if f"{evttype}:{port}" not in ports:
+ ev = SpiderFootEvent(evttype, entity, self.__name__, event)
+ self.notifyListeners(ev)
+ ports.append(f"{evttype}:{port}")
+
+ try:
+ banner = prec['result']['data']['service']['banner']
+ if '\\r\\n\\r\\n' in banner and "HTTP/" in banner:
+ # We don't want the content after HTTP banners
+ banner = banner.split('\\r\\n\\r\\n')[0]
+ banner = banner.replace("\\r\\n", "\n")
+ except Exception:
+ self.debug("No banner information found.")
+ continue
+
+ e = SpiderFootEvent(evtbtype, banner, self.__name__, ev)
+ self.notifyListeners(e)
+
+ for addr in qrylist:
+ self.checkedips[addr] = True
+
+# End of sfp_binaryedge class
diff --git a/spiderfoot/modules/sfp_bingsearch.py b/spiderfoot/modules/sfp_bingsearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb2ccc752d47bb8a572d269175e7fde9a29db2ff
--- /dev/null
+++ b/spiderfoot/modules/sfp_bingsearch.py
@@ -0,0 +1,133 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bingsearch
+# Purpose: Searches Bing for content related to the domain in question.
+#
+# Author: Steve Micallef
+#
+# Created: 06/10/2013
+# Copyright: (c) Steve Micallef 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bingsearch(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Bing",
+ 'summary': "Obtain information from bing to identify sub-domains and links.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://www.bing.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://azure.microsoft.com/en-in/services/cognitive-services/bing-web-search-api/",
+ "Register a free account",
+ "Select on Bing Custom Search",
+ "The API keys are listed under 'Key1' and 'Key2' (both should work)"
+ ],
+ 'favIcon': "https://www.bing.com/sa/simg/bing_p_rr_teal_min.ico",
+ 'logo': "https://www.bing.com/sa/simg/bing_p_rr_teal_min.ico",
+ 'description': "The Bing Search APIs let you build web-connected apps and services that "
+ "find webpages, images, news, locations, and more without advertisements.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "pages": 20,
+ "api_key": ""
+ }
+
+ # Option descriptions
+ optdescs = {
+ "pages": "Number of max bing results to request from the API.",
+ "api_key": "Bing API Key for Bing search."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["LINKED_URL_INTERNAL", "RAW_RIR_DATA"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_bingsearch but did not set a Bing API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug("Already did a search for " + eventData + ", skipping.")
+ return
+
+ self.results[eventData] = True
+
+ # Sites hosted on the domain
+
+ res = self.sf.bingIterate(
+ searchString="site:" + eventData,
+ opts={
+ "timeout": self.opts["_fetchtimeout"],
+ "useragent": self.opts["_useragent"],
+ "count": self.opts["pages"],
+ "api_key": self.opts["api_key"],
+ },
+ )
+ if res is None:
+ # Failed to talk to the bing API or no results returned
+ return
+
+ urls = res["urls"]
+ new_links = list(set(urls) - set(self.results.keys()))
+
+ # Add new links to results
+ for link in new_links:
+ self.results[link] = True
+
+ internal_links = [
+ link for link in new_links if self.sf.urlFQDN(link).endswith(eventData)
+ ]
+ for link in internal_links:
+ self.debug("Found a link: " + link)
+
+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if internal_links:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(res), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_bingsearch class
diff --git a/spiderfoot/modules/sfp_bingsharedip.py b/spiderfoot/modules/sfp_bingsharedip.py
new file mode 100644
index 0000000000000000000000000000000000000000..abf7f4dc658b7f4a9d1bda6330c785637d97b4d2
--- /dev/null
+++ b/spiderfoot/modules/sfp_bingsharedip.py
@@ -0,0 +1,184 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bingsharedip
+# Purpose: Searches Bing for hosts sharing the same IP.
+#
+# Author: Steve Micallef
+#
+# Created: 12/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bingsharedip(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Bing (Shared IPs)",
+ 'summary': "Search Bing for hosts sharing the same IP.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://www.bing.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://azure.microsoft.com/en-in/services/cognitive-services/bing-web-search-api/",
+ "Register a free account",
+ "Select on Bing Custom Search",
+ "The API keys are listed under 'Key1' and 'Key2' (both should work)"
+ ],
+ 'favIcon': "https://www.bing.com/sa/simg/bing_p_rr_teal_min.ico",
+ 'logo': "https://www.bing.com/sa/simg/bing_p_rr_teal_min.ico",
+ 'description': "The Bing Search APIs let you build web-connected apps and services that "
+ "find webpages, images, news, locations, and more without advertisements.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "cohostsamedomain": False,
+ "pages": 20,
+ "verify": True,
+ "maxcohost": 100,
+ "api_key": ""
+ }
+
+ # Option descriptions
+ optdescs = {
+ "cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",
+ "pages": "Number of max bing results to request from API.",
+ "verify": "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ "maxcohost": "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ "api_key": "Bing API Key for shared IP search."
+ }
+
+ results = None
+ cohostcount = 0
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+ self.__dataSource__ = "Bing"
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "NETBLOCK_OWNER"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["CO_HOSTED_SITE", "IP_ADDRESS", "RAW_RIR_DATA"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ self.currentEventSrc = event
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "" and self.opts['api_key'] == "":
+ self.error("You enabled sfp_bingsharedip but did not set a Bing API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ # Ignore IP addresses from myself as they are just for creating
+ # a link from the netblock to the co-host.
+ if eventName == "IP_ADDRESS" and srcModuleName == "sfp_bingsharedip":
+ self.debug("Ignoring " + eventName + ", from self.")
+ return
+
+ if self.cohostcount > self.opts["maxcohost"]:
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ if str(ipaddr) not in self.results:
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+ self.results[eventData] = True
+
+ myres = list()
+
+ for ip in qrylist:
+ if self.checkForStop():
+ return
+
+ res = self.sf.bingIterate(
+ searchString="ip:" + ip,
+ opts={
+ "timeout": self.opts["_fetchtimeout"],
+ "useragent": self.opts["_useragent"],
+ "count": self.opts["pages"],
+ "api_key": self.opts["api_key"],
+ },
+ )
+ if res is None:
+ # Failed to talk to bing api or no results returned
+ return
+
+ urls = res["urls"]
+
+ for url in urls:
+ self.info("Found something on same IP: " + url)
+ site = self.sf.urlFQDN(url.lower())
+ if site not in myres and site != ip:
+ if not self.opts["cohostsamedomain"]:
+ if self.getTarget().matches(site, includeParents=True):
+ self.debug(
+ f"Skipping {site} because it is on the same domain."
+ )
+ continue
+ if self.opts["verify"] and not self.sf.validateIP(site, ip):
+ self.debug(f"Host {site} no longer resolves to {ip}")
+ continue
+ # Create an IP Address event stemming from the netblock as the
+ # link to the co-host.
+ if eventName == "NETBLOCK_OWNER":
+ ipe = SpiderFootEvent("IP_ADDRESS", ip, self.__name__, event)
+ self.notifyListeners(ipe)
+ evt = SpiderFootEvent(
+ "CO_HOSTED_SITE", site, self.__name__, ipe
+ )
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent(
+ "CO_HOSTED_SITE", site, self.__name__, event
+ )
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+ myres.append(site)
+
+ if urls:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(res), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_bingsharedip class
diff --git a/spiderfoot/modules/sfp_binstring.py b/spiderfoot/modules/sfp_binstring.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cae6f58793492e31288c7924d7469ec8ce8c227
--- /dev/null
+++ b/spiderfoot/modules/sfp_binstring.py
@@ -0,0 +1,149 @@
+# coding: utf-8
+# -------------------------------------------------------------------------------
+# Name: sfp_binstring
+# Purpose: Identify strings in binary content.
+#
+# Author: Steve Micallef
+#
+# Created: 03/12/2016
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import string
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_binstring(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Binary String Extractor",
+ 'summary': "Attempt to identify strings in binary content.",
+ 'flags': ["errorprone"],
+ 'useCases': ["Footprint"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ 'minwordsize': 5,
+ 'maxwords': 100,
+ 'maxfilesize': 1000000,
+ 'usedict': True,
+ 'fileexts': ['png', 'gif', 'jpg', 'jpeg', 'tiff', 'tif',
+ 'ico', 'flv', 'mp4', 'mp3', 'avi', 'mpg',
+ 'mpeg', 'dat', 'mov', 'swf', 'exe', 'bin'],
+ 'filterchars': '#}{|%^&*()=+,;[]~'
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'minwordsize': "Upon finding a string in a binary, ensure it is at least this length. Helps weed out false positives.",
+ 'usedict': "Use the dictionary to further reduce false positives - any string found must contain a word from the dictionary (can be very slow, especially for larger files).",
+ 'fileexts': "File types to fetch and analyse.",
+ 'maxfilesize': "Maximum file size in bytes to download for analysis.",
+ 'maxwords': "Stop reporting strings from a single binary after this many are found.",
+ 'filterchars': "Ignore strings with these characters, as they may just be garbage ASCII."
+ }
+
+ results = list()
+ d = None
+ n = None
+ fq = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = list()
+ self.__dataSource__ = "Target Website"
+
+ self.d = SpiderFootHelpers.dictionaryWordsFromWordlists()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def getStrings(self, content):
+ words = list()
+ result = ""
+
+ if not content:
+ return None
+
+ for c in content:
+ c = str(c)
+ if len(words) >= self.opts['maxwords']:
+ break
+ if c in string.printable and c not in string.whitespace:
+ result += c
+ continue
+ if len(result) >= self.opts['minwordsize']:
+ if self.opts['usedict']:
+ accept = False
+ for w in self.d:
+ if result.startswith(w) or result.endswith(w):
+ accept = True
+ break
+
+ if self.opts['filterchars']:
+ accept = True
+ for x in self.opts['filterchars']:
+ if x in result:
+ accept = False
+ break
+
+ if not self.opts['filterchars'] and not self.opts['usedict']:
+ accept = True
+
+ if accept:
+ words.append(result)
+
+ result = ""
+
+ if len(words) == 0:
+ return None
+
+ return words
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["RAW_FILE_META_DATA"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ return
+
+ self.results.append(eventData)
+
+ for fileExt in self.opts['fileexts']:
+ if eventData.lower().endswith(f".{fileExt.lower()}") or f".{fileExt.lower()}?" in eventData.lower():
+ res = self.sf.fetchUrl(
+ eventData,
+ useragent=self.opts['_useragent'],
+ disableContentEncoding=True,
+ sizeLimit=self.opts['maxfilesize'],
+ verify=False
+ )
+
+ if not res:
+ continue
+
+ self.debug(f"Searching {eventData} for strings")
+ words = self.getStrings(res['content'])
+
+ if words:
+ wordstr = '\n'.join(words[0:self.opts['maxwords']])
+ evt = SpiderFootEvent("RAW_FILE_META_DATA", wordstr, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_binstring class
diff --git a/spiderfoot/modules/sfp_bitcoin.py b/spiderfoot/modules/sfp_bitcoin.py
new file mode 100644
index 0000000000000000000000000000000000000000..f04532fea5acea48a30d0e59dcdc62c848f0def3
--- /dev/null
+++ b/spiderfoot/modules/sfp_bitcoin.py
@@ -0,0 +1,96 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bitcoin
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying bitcoin numbers.
+#
+# Author: Steve Micallef
+#
+# Created: 27/05/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import codecs
+import re
+from hashlib import sha256
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bitcoin(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Bitcoin Finder",
+ 'summary': "Identify bitcoin addresses in scraped webpages.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {}
+ optdescs = {}
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT"]
+
+ def producedEvents(self):
+ return ["BITCOIN_ADDRESS"]
+
+ def to_bytes(self, n, length):
+ h = '%x' % n
+ return codecs.decode(('0' * (len(h) % 2) + h).zfill(length * 2), "hex")
+
+ def decode_base58(self, bc, length):
+ digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+ n = 0
+ for char in bc:
+ n = n * 58 + digits58.index(char)
+ return self.to_bytes(n, length)
+
+ def check_bc(self, bc):
+ bcbytes = self.decode_base58(bc, 25)
+ return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ sourceData = self.sf.hashstring(eventData)
+
+ if sourceData in self.results:
+ return
+
+ self.results[sourceData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ addrs = list()
+
+ # thanks to https://stackoverflow.com/questions/21683680/regex-to-match-bitcoin-addresses
+ # Does not support keys or testnet addresses
+ matches = re.findall(r"[\s:=\>](bc(0([ac-hj-np-z02-9]{39}|[ac-hj-np-z02-9]{59})|1[ac-hj-np-z02-9]{8,87})|[13][a-km-zA-HJ-NP-Z1-9]{25,35})", eventData)
+ for m in matches:
+ address = m[0]
+ self.debug(f"Potential Bitcoin address match: {address}")
+
+ if address.startswith('1') or address.startswith('3'):
+ if self.check_bc(address):
+ addrs.append(address)
+ else:
+ addrs.append(address)
+
+ for address in set(addrs):
+ evt = SpiderFootEvent("BITCOIN_ADDRESS", address, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_bitcoin class
diff --git a/spiderfoot/modules/sfp_bitcoinabuse.py b/spiderfoot/modules/sfp_bitcoinabuse.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a9e4999ab7f210ca1b9b6c3ec033fce667e1c79
--- /dev/null
+++ b/spiderfoot/modules/sfp_bitcoinabuse.py
@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bitcoinabuse
+# Purpose: Check bitcoin address agains bitcoinabuse.com database
+#
+# Author: Leo Trubach
+#
+# Created: 2020-09-01
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.parse
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bitcoinabuse(SpiderFootPlugin):
+ meta = {
+ "name": "BitcoinAbuse",
+ "summary": "Check Bitcoin addresses against the bitcoinabuse.com database of suspect/malicious addresses.",
+ 'flags': ["apikey"],
+ "useCases": ["Passive", "Investigate"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://www.bitcoinabuse.com/",
+ "model": "FREE_AUTH_UNLIMITED",
+ "references": ["https://www.bitcoinabuse.com/api-docs"],
+ "apiKeyInstructions": [
+ "Visit https://www.bitcoinabuse.com/register",
+ "Register a free account",
+ "Click on the account icon and click on 'Your Settings'",
+ "Click on 'API'",
+ "Enter a token name and press 'Create'",
+ ],
+ "favIcon": "https://www.bitcoinabuse.com/favicon-32x32.png",
+ "logo": "https://www.bitcoinabuse.com/img/logo-sm.png",
+ "description": "BitcoinAbuse.com is a public database of bitcoin "
+ "addresses used by scammers, hackers, and criminals."
+ "Bitcoin is anonymous if used perfectly. Luckily, no "
+ "one is perfect. Even hackers make mistakes. It only "
+ "takes one slip to link stolen bitcoin to a hacker's "
+ "their real identity. It is our hope that by making a "
+ "public database of bitcoin addresses used by criminals it "
+ "will be harder for criminals to convert the digital currency"
+ " back into fiat money.",
+ },
+ }
+ opts = {
+ "api_key": "",
+ }
+ optdescs = {
+ "api_key": "BitcoinAbuse API Key.",
+ }
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=None):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ if userOpts:
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return ["BITCOIN_ADDRESS"]
+
+ def producedEvents(self):
+ return [
+ "MALICIOUS_BITCOIN_ADDRESS",
+ "RAW_RIR_DATA",
+ ]
+
+ def queryAddress(self, address: str):
+ params = {
+ "address": address,
+ "api_token": self.opts["api_key"]
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://www.bitcoinabuse.com/api/reports/check?{urllib.parse.urlencode(params)}",
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+
+ # All endpoints other than Report Address have a rate limit of
+ # 30 requests per minute or one request every two seconds on average.
+ time.sleep(2)
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from BitcoinAbuse.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results for query")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid BitcoinAbuse API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by BitcoinAbuse")
+ self.errorState = True
+ return None
+
+ if res['code'] in ['500', '502', '503']:
+ self.error("BitcoinAbuse service unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all other non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from BitcoinAbuse")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from BitcoinAbuse: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ eventName = event.eventType
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if self.opts["api_key"] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "BITCOIN_ADDRESS":
+ rec = self.queryAddress(eventData)
+
+ if not rec:
+ return
+
+ if not isinstance(rec, dict):
+ return
+
+ count = rec.get("count")
+
+ if not count:
+ return
+
+ if not isinstance(count, int):
+ return
+
+ address = rec.get('address')
+
+ if not address:
+ return
+
+ url = f"https://www.bitcoinabuse.com/reports/{address}"
+ evt = SpiderFootEvent(
+ "MALICIOUS_BITCOIN_ADDRESS",
+ f"BitcoinAbuse [{address}]\n{url} ",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ rirevt = SpiderFootEvent(
+ "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
+ )
+ self.notifyListeners(rirevt)
diff --git a/spiderfoot/modules/sfp_bitcoinwhoswho.py b/spiderfoot/modules/sfp_bitcoinwhoswho.py
new file mode 100644
index 0000000000000000000000000000000000000000..61786fa48326ce06d3e8b059784b041b0448c3ac
--- /dev/null
+++ b/spiderfoot/modules/sfp_bitcoinwhoswho.py
@@ -0,0 +1,133 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_bitcoinwhoswho
+# Purpose: Bitcoin Who's Who database lookup module
+#
+# Author: Leo Trubach
+#
+# Created: 2020-09-09
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib.parse
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_bitcoinwhoswho(SpiderFootPlugin):
+ meta = {
+ 'name': "Bitcoin Who's Who",
+ 'summary': "Check for Bitcoin addresses against the Bitcoin Who's Who database of suspect/malicious addresses.",
+ 'flags': ["apikey"],
+ 'useCases': ["Passive", "Investigate"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://bitcoinwhoswho.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://bitcoinwhoswho.com/api"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://bitcoinwhoswho.com/signup",
+ "Register a free account",
+ "Verify your email and sign into your account",
+ "Visit https://bitcoinwhoswho.com/api/register and request an API Key",
+ "Wait for a few days, you'll receive it to your email"
+ ],
+ 'favIcon': "https://bitcoinwhoswho.com/public/images/ico/favicon.ico",
+ 'logo': "https://bitcoinwhoswho.com/public/images/logo2.png",
+ 'description': (
+ "Bitcoin Who's Who is dedicated to profiling the extraordinary members of the bitcoin "
+ "ecosystem.Our goal is to help you verify a bitcoin address owner and avoid a bitcoin "
+ "scam or fraud."
+ ),
+ }
+ }
+
+ opts = {
+ 'api_key': '',
+ }
+
+ optdescs = {
+ "api_key": "Bitcoin Who's Who API Key."
+ }
+
+ results = None
+
+ errorState = False
+
+ def setup(self, sfc, userOpts=None):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ if userOpts:
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return ["BITCOIN_ADDRESS"]
+
+ def producedEvents(self):
+ return ["MALICIOUS_BITCOIN_ADDRESS", "RAW_RIR_DATA"]
+
+ def query(self, qry):
+ qs = urllib.parse.urlencode({"address": qry})
+ res = self.sf.fetchUrl(
+ f"https://bitcoinwhoswho.com/api/scam/{self.opts['api_key']}?{qs}",
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+
+ if res["content"] is None:
+ self.info(f"No {self.meta['name']} info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res["content"])
+ except Exception as e:
+ self.error(f"Error processing JSON response from {self.meta['name']}: {e}")
+
+ return None
+
+ def emit(self, etype, data, pevent, notify=True):
+ evt = SpiderFootEvent(etype, data, self.__name__, pevent)
+ if notify:
+ self.notifyListeners(evt)
+ return evt
+
+ def generate_events(self, data, pevent):
+ if not isinstance(data, dict):
+ return False
+
+ scams = data.get("scams", [])
+ if scams:
+ self.emit("MALICIOUS_BITCOIN_ADDRESS", f"Bitcoin Who's Who [{pevent.data}][https://bitcoinwhoswho.com/address/{pevent.data}]", pevent)
+ return True
+
+ return False
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ if self.opts["api_key"] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ if event.data in self.results:
+ self.debug(f"Skipping {event.data}, already checked.")
+ return
+ self.results[event.data] = True
+
+ if event.eventType == "BITCOIN_ADDRESS":
+ data = self.query(event.data)
+ r = self.generate_events(data, event)
+
+ if r:
+ self.emit("RAW_RIR_DATA", json.dumps(data), event)
+
+# End of sfp_bitcoinwhoswho class
diff --git a/spiderfoot/modules/sfp_blockchain.py b/spiderfoot/modules/sfp_blockchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1198a895a2eb8a6266f1ff4435182bcafc34df3
--- /dev/null
+++ b/spiderfoot/modules/sfp_blockchain.py
@@ -0,0 +1,98 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_blockchain
+# Purpose: SpiderFoot plug-in to look up a bitcoin wallet's balance by
+# querying blockchain.info.
+#
+# Author: Steve Micallef
+#
+# Created: 18/06/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_blockchain(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Blockchain",
+ 'summary': "Queries blockchain.info to find the balance of identified bitcoin wallet addresses.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Public Registries"],
+ 'dataSource': {
+ 'website': "https://www.blockchain.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://exchange.blockchain.com/api/#introduction",
+ "https://exchange.blockchain.com/markets",
+ "https://exchange.blockchain.com/fees",
+ "https://exchange.blockchain.com/trade"
+ ],
+ 'favIcon': "https://www.blockchain.com/static/favicon.ico",
+ 'logo': "https://exchange.blockchain.com/api/assets/images/logo.png",
+ 'description': "Blockchain Exchange is the most secure place to buy, sell, and trade crypto.\n"
+ "Use the most popular block explorer to search and "
+ "verify transactions on the Bitcoin, Ethereum, and Bitcoin Cash blockchains.\n"
+ "Stay on top of Bitcoin and other top cryptocurrency prices, news, and market information.",
+ }
+ }
+
+ # Default options
+ opts = {}
+ optdescs = {}
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['BITCOIN_ADDRESS']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["BITCOIN_BALANCE"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ # Wallet balance
+ res = self.sf.fetchUrl("https://blockchain.info/balance?active=" + eventData,
+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+ if res['content'] is None:
+ self.info("No Blockchain info found for " + eventData)
+ return
+ try:
+ data = json.loads(res['content'])
+ balance = float(data[eventData]['final_balance']) / 100000000
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return
+
+ evt = SpiderFootEvent("BITCOIN_BALANCE", str(balance) + " BTC", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_blockchain class
diff --git a/spiderfoot/modules/sfp_blocklistde.py b/spiderfoot/modules/sfp_blocklistde.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b7195940dc0720796f5ca59e590dcb627b1405
--- /dev/null
+++ b/spiderfoot/modules/sfp_blocklistde.py
@@ -0,0 +1,217 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_blocklistde
+# Purpose: Check if a netblock or IP is malicious according to blocklist.de.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_blocklistde(SpiderFootPlugin):
+
+ meta = {
+ 'name': "blocklist.de",
+ 'summary': "Check if a netblock or IP is malicious according to blocklist.de.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "http://www.blocklist.de/en/index.html",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "http://www.blocklist.de/en/api.html",
+ "http://www.blocklist.de/en/rbldns.html",
+ "http://www.blocklist.de/en/httpreports.html",
+ "http://www.blocklist.de/en/export.html",
+ "http://www.blocklist.de/en/delist.html?ip="
+ ],
+ 'favIcon': "http://www.blocklist.de/templates/css/logo_web-size.jpg",
+ 'logo': "http://www.blocklist.de/templates/css/logo_web-size.jpg",
+ 'description': "www.blocklist.de is a free and voluntary service provided by a Fraud/Abuse-specialist, "
+ "whose servers are often attacked via SSH-, Mail-Login-, FTP-, Webserver- and other services.\n"
+ "The mission is to report any and all attacks to the respective abuse departments of the infected PCs/servers, "
+ "to ensure that the responsible provider can inform their customer about the infection and disable the attacker."
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ "NETBLOCK_MEMBER",
+ "NETBLOCKV6_MEMBER",
+ "NETBLOCK_OWNER",
+ "NETBLOCKV6_OWNER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ ]
+
+ def queryBlacklist(self, target, targetType):
+ blacklist = self.retrieveBlacklist()
+
+ if not blacklist:
+ return False
+
+ if targetType == "ip":
+ if target in blacklist:
+ self.debug(f"IP address {target} found in blocklist.de blacklist.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in blacklist:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in blocklist.de blacklist.")
+ return True
+
+ return False
+
+ def retrieveBlacklist(self):
+ blacklist = self.sf.cacheGet('blocklistde', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://lists.blocklist.de/lists/all.txt",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from blocklist.de.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from blocklist.de")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("blocklistde", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from blocklist.de
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ if not blacklist:
+ return ips
+
+ for ip in blacklist.split('\n'):
+ ip = ip.strip()
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip) and not self.sf.validIP6(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ targetType = 'ip'
+ malicious_type = 'MALICIOUS_IPADDR'
+ blacklist_type = 'BLACKLISTED_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = 'MALICIOUS_AFFILIATE_IPADDR'
+ blacklist_type = 'BLACKLISTED_AFFILIATE_IPADDR'
+ elif eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = 'MALICIOUS_NETBLOCK'
+ blacklist_type = 'BLACKLISTED_NETBLOCK'
+ elif eventName in ['NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = 'MALICIOUS_SUBNET'
+ blacklist_type = 'BLACKLISTED_SUBNET'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with blocklist.de")
+
+ if self.queryBlacklist(eventData, targetType):
+ # https://www.blocklist.de/en/search.html?ip=
+ url = "https://lists.blocklist.de/lists/all.txt"
+ text = f"blocklist.de [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_blocklistde class
diff --git a/spiderfoot/modules/sfp_botscout.py b/spiderfoot/modules/sfp_botscout.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c6dc5beaa19129c9c16f2f47a19f666e3ce9457
--- /dev/null
+++ b/spiderfoot/modules/sfp_botscout.py
@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_botscout
+# Purpose: SpiderFoot plug-in to search botsout.com using their API, for
+# potential malicious IPs and e-mail addresses.
+#
+# Author: Steve Micallef
+#
+# Created: 25/07/2016
+# Copyright: (c) Steve Micallef 2016
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_botscout(SpiderFootPlugin):
+
+ meta = {
+ 'name': "BotScout",
+ 'summary': "Searches BotScout.com's database of spam-bot IP addresses and e-mail addresses.",
+ 'flags': ["apikey"],
+ 'useCases': ["Passive", "Investigate"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://botscout.com/",
+ 'model': "FREE_NOAUTH_LIMITED",
+ 'references': [
+ "http://botscout.com/api.htm",
+ "http://botscout.com/api_queries.htm",
+ "http://botscout.com/getkey.htm",
+ "http://botscout.com/corp_users.htm"
+ ],
+ 'apiKeyInstructions': [
+ "Visit http://botscout.com/getkey.htm",
+ "Register a free account",
+ "The API key will be emailed to your account"
+ ],
+ 'favIcon': "https://botscout.com/favicon.ico",
+ 'logo': "http://botscout.com/image/bslogo.gif",
+ 'description': "BotScout helps prevent automated web scripts, known as \"bots\", "
+ "from registering on forums, polluting databases, spreading spam, "
+ "and abusing forms on web sites. We do this by tracking the names, IPs, "
+ "and email addresses that bots use and logging them as unique signatures for future reference. "
+ "We also provide a simple yet powerful API that you can use to test forms "
+ "when they're submitted on your site.",
+ }
+ }
+
+ opts = {
+ "api_key": ""
+ }
+ optdescs = {
+ "api_key": "Botscout.com API key. Without this you will be limited to 100 look-ups per day."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['IP_ADDRESS', 'EMAILADDR']
+
+ def producedEvents(self):
+ return ["MALICIOUS_IPADDR", "BLACKLISTED_IPADDR", "MALICIOUS_EMAILADDR"]
+
+ def queryIp(self, ip):
+ if not self.sf.validIP(ip):
+ return None
+
+ params = urllib.parse.urlencode({
+ 'ip': ip,
+ 'key': self.opts['api_key'],
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://botscout.com/test/?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ return self.parseApiResponse(res)
+
+ def queryEmail(self, email):
+ if not SpiderFootHelpers.validEmail(email):
+ return None
+
+ params = urllib.parse.urlencode({
+ 'mail': email,
+ 'key': self.opts['api_key'],
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://botscout.com/test/?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from BotScout.")
+ return None
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from BotScout.")
+ self.errorState = True
+ return None
+
+ if not res['content']:
+ self.error("No response from BotScout.")
+ return None
+
+ if res['content'].startswith("! "):
+ self.error(f"Received error from BotScout: {res['content']}")
+ self.errorState = True
+ return None
+
+ if not res['content'].startswith("Y|") and not res['content'].startswith("N|"):
+ self.error("Error encountered processing response from BotScout.")
+ return None
+
+ return res['content']
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if not self.opts['api_key']:
+ self.info("You enabled sfp_botscout but did not set an API key! Queries will be limited to 100 per day.")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData} as already searched.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "IP_ADDRESS":
+ res = self.queryIp(eventData)
+
+ if not res:
+ return
+
+ if not res.startswith("Y|"):
+ return
+
+ self.info(f"Found BotScout entry for {eventData}: {res}")
+
+ url = f"https://botscout.com/ipcheck.htm?ip={eventData}"
+ text = f"BotScout [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent("BLACKLISTED_IPADDR", text, self.__name__, event)
+ self.notifyListeners(evt)
+ elif eventName == "EMAILADDR":
+ res = self.queryEmail(eventData)
+
+ if not res:
+ return
+
+ if not res.startswith("Y|"):
+ return
+
+ url = f"https://botscout.com/search.htm?sterm={eventData}&stype=q"
+ text = f"BotScout [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent("MALICIOUS_EMAILADDR", text, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+
+# End of sfp_botscout class
diff --git a/spiderfoot/modules/sfp_botvrij.py b/spiderfoot/modules/sfp_botvrij.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2393ac62a6173b43285be91b753b8f19567291
--- /dev/null
+++ b/spiderfoot/modules/sfp_botvrij.py
@@ -0,0 +1,186 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_botvrij
+# Purpose: Check if a domain is malicious according to botvrij.eu.
+#
+# Author: steve@binarypool.com
+#
+# Created: 16/05/2020
+# Copyright: (c) Steve Micallef, 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_botvrij(SpiderFootPlugin):
+
+ meta = {
+ 'name': "botvrij.eu",
+ 'summary': "Check if a domain is malicious according to botvrij.eu.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://botvrij.eu/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'description': "Botvrij.eu provides different sets "
+ " of open source IOCs that you can use in your "
+ " security devices to detect possible malicious activity.\n"
+ "The information contains network info (IPs), file hashes,"
+ " file paths, domain names, URLs.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'cacheperiod': 18
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Hours to cache list data before re-fetching."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryBlacklist(self, target):
+ blacklist = self.retrieveBlacklist()
+
+ if not blacklist:
+ return False
+
+ if target.lower() in blacklist:
+ self.debug(f"Host name {target} found in botvrij.eu blacklist.")
+ return True
+
+ return False
+
+ def retrieveBlacklist(self):
+ blacklist = self.sf.cacheGet('botvrij', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://www.botvrij.eu/data/blocklist/blocklist_full.csv",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from botvrij.eu.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from botvrij.eu")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("botvrij", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from botvrij.eu
+
+ Returns:
+ list: list of blacklisted host names
+ """
+ hosts = list()
+
+ if not blacklist:
+ return hosts
+
+ for line in blacklist.split('\n'):
+ if not line:
+ continue
+ if line.startswith('#'):
+ continue
+ host = line.strip().split(",")[0].lower()
+ # Note: Validation with sf.validHost() is too slow to use here
+ # if not self.sf.validHost(host, self.opts['_internettlds']):
+ # continue
+ hosts.append(host)
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with botvrij.eu")
+
+ if not self.queryBlacklist(eventData):
+ return
+
+ url = "https://www.botvrij.eu/data/blocklist/blocklist_full.csv"
+ text = f"botvrij.eu Domain Blocklist [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_botvrij class
diff --git a/spiderfoot/modules/sfp_builtwith.py b/spiderfoot/modules/sfp_builtwith.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d52b41e8deaf0b7d2f40d9de3ac345744cbe11c
--- /dev/null
+++ b/spiderfoot/modules/sfp_builtwith.py
@@ -0,0 +1,270 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_builtwith
+# Purpose: Query builtwith.com using their API.
+#
+# Author: Steve Micallef
+#
+# Created: 10/08/2017
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_builtwith(SpiderFootPlugin):
+
+ meta = {
+ 'name': "BuiltWith",
+ 'summary': "Query BuiltWith.com's Domain API for information about your target's web technology stack, e-mail addresses and more.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://builtwith.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://api.builtwith.com/",
+ "https://kb.builtwith.com/",
+ "https://builtwith.com/screencast",
+ "https://builtwith.com/faq"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://api.builtwith.com/free-api",
+ "Register a free account",
+ "Navigate to https://api.builtwith.com/free-api",
+ "The API key is listed under 'Your API Key'"
+ ],
+ 'favIcon': "https://d28rh9vvmrd65v.cloudfront.net/favicon.ico",
+ 'logo': "https://d28rh9vvmrd65v.cloudfront.net/favicon.ico",
+ 'description': "Build lists of websites from our database of 38,701+ web technologies and over a quarter of a billion websites showing "
+ "which sites use shopping carts, analytics, hosting and many more. "
+ "Filter by location, traffic, vertical and more.\n"
+ "Know your prospects platform before you talk to them. "
+ "Improve your conversions with validated market adoption.\n"
+ "Get advanced technology market share information and country based analytics for all web technologies.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "maxage": 30
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "Builtwith.com Domain API key.",
+ "maxage": "The maximum age of the data returned, in days, in order to be considered valid."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["INTERNET_NAME", "EMAILADDR", "EMAILADDR_GENERIC", "RAW_RIR_DATA",
+ "WEBSERVER_TECHNOLOGY", "PHONE_NUMBER", "DOMAIN_NAME",
+ "CO_HOSTED_SITE", "IP_ADDRESS", "WEB_ANALYTICS_ID"]
+
+ def queryRelationships(self, t):
+ url = f"https://api.builtwith.com/rv1/api.json?LOOKUP={t}&KEY={self.opts['api_key']}"
+
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
+
+ if res['code'] == "404":
+ return None
+
+ if not res['content']:
+ return None
+
+ try:
+ return json.loads(res['content'])['Relationships']
+ except Exception as e:
+ self.error(f"Error processing JSON response from builtwith.com: {e}")
+
+ return None
+
+ def queryDomainInfo(self, t):
+ url = f"https://api.builtwith.com/rv1/api.json?LOOKUP={t}&KEY={self.opts['api_key']}"
+
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
+
+ if res['code'] == "404":
+ return None
+
+ if not res['content']:
+ return None
+
+ try:
+ return json.loads(res['content'])['Results'][0]
+ except Exception as e:
+ self.error(f"Error processing JSON response from builtwith.com: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_builtwith but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.queryDomainInfo(eventData)
+ if data is not None:
+ if "Meta" in data:
+ if data['Meta'].get("Names", []):
+ for nb in data['Meta']['Names']:
+ e = SpiderFootEvent("RAW_RIR_DATA", "Possible full name: " + nb['Name'],
+ self.__name__, event)
+ self.notifyListeners(e)
+ if nb.get('Email', None):
+ if SpiderFootHelpers.validEmail(nb['Email']):
+ if nb['Email'].split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+ e = SpiderFootEvent(evttype, nb['Email'],
+ self.__name__, event)
+ self.notifyListeners(e)
+
+ if data['Meta'].get("Emails", []):
+ for email in data['Meta']['Emails']:
+ if SpiderFootHelpers.validEmail(email):
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ e = SpiderFootEvent(evttype, email,
+ self.__name__, event)
+ self.notifyListeners(e)
+
+ if data['Meta'].get("Telephones", []):
+ for phone in data['Meta']['Telephones']:
+ phone = phone.replace("-", "").replace("(", "").replace(")", "").replace(" ", "")
+ e = SpiderFootEvent("PHONE_NUMBER", phone, self.__name__, event)
+ self.notifyListeners(e)
+
+ if "Paths" in data.get("Result", []):
+ for p in data["Result"]['Paths']:
+ if p.get("SubDomain", ""):
+ h = p["SubDomain"] + "." + eventData
+ ev = SpiderFootEvent("INTERNET_NAME", h, self.__name__, event)
+ self.notifyListeners(ev)
+ if self.sf.isDomain(h, self.opts['_internettlds']):
+ ev = SpiderFootEvent("DOMAIN_NAME", h, self.__name__, event)
+ self.notifyListeners(ev)
+ else:
+ ev = None
+
+ # If we have a subdomain, let's get its tech info
+ # and associate it with the subdomain event.
+ for t in p.get("Technologies", []):
+ if ev:
+ src = ev
+ else:
+ src = event
+ agelimit = int(time.time() * 1000) - (86400000 * self.opts['maxage'])
+ if t.get("LastDetected", 0) < agelimit:
+ self.debug("Data found too old, skipping.")
+ continue
+ e = SpiderFootEvent("WEBSERVER_TECHNOLOGY", t["Name"],
+ self.__name__, src)
+ self.notifyListeners(e)
+
+ data = self.queryRelationships(eventData)
+ if data is None:
+ return
+
+ agelimit = int(time.time() * 1000) - (86400000 * self.opts['maxage'])
+
+ for r in data:
+ if "Domain" not in r or "Identifiers" not in r:
+ self.debug("Data returned not in the format requested.")
+ continue
+
+ if r['Domain'] != eventData:
+ self.debug("Data returned doesn't match data requested, skipping.")
+ continue
+
+ for i in r['Identifiers']:
+ if "Last" not in i or "Type" not in i or "Value" not in i:
+ self.debug("Data returned not in the format requested.")
+ continue
+
+ if i['Last'] < agelimit:
+ self.debug("Data found too old, skipping.")
+ continue
+
+ evttype = None
+ # Related through shared IP
+ if i['Type'] == "ip":
+ if self.sf.validIP(i['Value']):
+ val = i['Value']
+ evttype = "IP_ADDRESS"
+ else:
+ val = i['Value'].strip(".")
+ if self.getTarget.matches(val):
+ evttype = "INTERNET_NAME"
+ else:
+ evttype = "CO_HOSTED_SITE"
+
+ # Create the name/co-host
+ e = SpiderFootEvent(evttype, val, self.__name__, event)
+ self.notifyListeners(e)
+ continue
+
+ # Related through shared analytics ID
+ txt = i['Type'] + ": " + str(i['Value'])
+ e = SpiderFootEvent("WEB_ANALYTICS_ID", txt, self.__name__, event)
+ self.notifyListeners(e)
+
+ if i['Matches']:
+ for m in i['Matches']:
+ if "Domain" not in m:
+ continue
+ evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME", m['Domain'], self.__name__, e)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(m['Domain'], self.opts['_internettlds']):
+ evt = SpiderFootEvent("AFFILIATE_DOMAIN_NAME", m['Domain'], self.__name__, e)
+ self.notifyListeners(evt)
+
+# End of sfp_builtwith class
diff --git a/spiderfoot/modules/sfp_c99.py b/spiderfoot/modules/sfp_c99.py
new file mode 100644
index 0000000000000000000000000000000000000000..5291a3c59bffd0ed76a560aa5c24619ff4ee5afa
--- /dev/null
+++ b/spiderfoot/modules/sfp_c99.py
@@ -0,0 +1,469 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_c99
+# Purpose: SpiderFoot plug-in that queries c99 API
+#
+# Author: Filip Aleksić
+#
+# Created: 2020-08-27
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_c99(SpiderFootPlugin):
+ meta = {
+ "name": "C99",
+ "summary": "Queries the C99 API which offers various data (geo location, proxy detection, phone lookup, etc).",
+ 'flags': ["apikey"],
+ "useCases": ["Footprint", "Passive", "Investigate"],
+ "categories": ["Search Engines"],
+ "dataSource": {
+ "website": "https://api.c99.nl/",
+ "model": "COMMERCIAL_ONLY",
+ "references": ["https://api.c99.nl/api_overview", "https://api.c99.nl/faq"],
+ "apiKeyInstructions": [
+ "Visit https://api.c99.nl",
+ "Click shop in the top navigation or go to https://api.c99.nl/dashboard/shop",
+ "Click purchase key on option 'C99.NL API KEY' (you can also purchase a 1 year key)",
+ "You will receive your API key by email.",
+ ],
+ "favIcon": "https://api.c99.nl/favicon.ico",
+ "logo": "https://api.c99.nl/assets/images/logo.png",
+ "description": "C99 API service is versatile source of information. "
+ "They offer over 57 different APIs of which 10 are integrated in this module. "
+ "APIs that are integrated are subdomain finder, phone lookup, Skype resolver, "
+ "IP to Skype, firewall technology WAF detector, domain history, "
+ "IP to domains, IP geo location, proxy detector.",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ "verify": True,
+ "cohostsamedomain": False,
+ "maxcohost": 100,
+ }
+
+ optdescs = {
+ "api_key": "C99 API Key.",
+ "verify": "Verify identified domains still resolve to the associated specified IP address.",
+ "maxcohost": "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ "cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ "PHONE_NUMBER",
+ "IP_ADDRESS",
+ "USERNAME",
+ "EMAILADDR",
+ ]
+
+ def producedEvents(self):
+ return [
+ "RAW_RIR_DATA",
+ "GEOINFO",
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "PROVIDER_TELCO",
+ "PHYSICAL_ADDRESS",
+ "PHYSICAL_COORDINATES",
+ "PROVIDER_DNS",
+ "IP_ADDRESS",
+ "USERNAME",
+ "ACCOUNT_EXTERNAL_OWNED",
+ "WEBSERVER_TECHNOLOGY",
+ "PROVIDER_HOSTING",
+ "CO_HOSTED_SITE"
+ ]
+
+ def query(self, path, queryParam, queryData):
+ res = self.sf.fetchUrl(
+ f"https://api.c99.nl/{path}?key={self.opts['api_key']}&{queryParam}={queryData}&json",
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+
+ if res["code"] == "429":
+ self.error("Reaching rate limit on C99 API")
+ self.errorState = True
+ return None
+
+ if res["code"] == 400:
+ self.error("Invalid request or API key on C99 API")
+ self.errorState = True
+ return None
+
+ if res["content"] is None:
+ self.info(f"No C99 info found for {queryData}")
+ return None
+
+ try:
+ info = json.loads(res["content"])
+ except Exception as e:
+ self.errorState = True
+ self.error(f"Error processing response from C99: {e}")
+ return None
+
+ if not info.get('success', False):
+ return None
+
+ return info
+
+ def emitRawRirData(self, data, event):
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ def emitPhoneData(self, phoneData, event):
+ provider = phoneData.get("provider")
+ carrier = phoneData.get("carrier")
+ city = phoneData.get("city")
+ countryName = phoneData.get("country_name")
+ region = phoneData.get("region")
+ found = False
+
+ if provider or carrier:
+ evt = SpiderFootEvent(
+ "PROVIDER_TELCO",
+ f"Provider: {provider}, Carrier: {carrier}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if city or countryName or region:
+ evt = SpiderFootEvent(
+ "PHYSICAL_ADDRESS",
+ f"Country: {countryName}, Region: {region}, City: {city}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ self.emitRawRirData(phoneData, event)
+
+ def emitSubDomainData(self, subDomainData, event):
+ found = False
+
+ for subDomainElem in subDomainData:
+ if self.checkForStop():
+ return
+
+ subDomain = subDomainElem.get("subdomain", "").strip()
+
+ if subDomain:
+ self.emitHostname(subDomain, event)
+ found = True
+
+ if found:
+ self.emitRawRirData(subDomainData, event)
+
+ def emitDomainHistoryData(self, domainHistoryData, event):
+ found = False
+
+ for domainHistoryElem in domainHistoryData:
+ if self.checkForStop():
+ return
+
+ ip = domainHistoryElem.get("ip_address")
+
+ if self.sf.validIP(ip):
+ evt = SpiderFootEvent(
+ "IP_ADDRESS",
+ ip,
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ self.emitRawRirData(domainHistoryData, event)
+
+ def emitIpToSkypeData(self, data, event):
+ skype = data.get("skype")
+
+ if skype:
+ evt = SpiderFootEvent(
+ "ACCOUNT_EXTERNAL_OWNED",
+ f"Skype [{skype}]",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(
+ "USERNAME",
+ skype,
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+
+ self.emitRawRirData(data, event)
+
+ def emitIpToDomainsData(self, data, event):
+ domains = data.get("domains")
+ found = False
+
+ if isinstance(domains, list):
+ for domain in domains:
+ if self.checkForStop():
+ return
+
+ domain = domain.strip()
+ if domain:
+ self.emitHostname(domain, event)
+ found = True
+
+ if found:
+ self.emitRawRirData(data, event)
+
+ def emitProxyDetectionData(self, data, event):
+ isProxy = data.get("proxy")
+
+ if isProxy:
+ evt = SpiderFootEvent(
+ "WEBSERVER_TECHNOLOGY",
+ f"Server is proxy: {isProxy}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ self.emitRawRirData(data, event)
+
+ def emitGeoIPData(self, data, event):
+ found = False
+
+ hostName = data.get("hostname", "").strip()
+ if hostName:
+ self.emitHostname(hostName, event)
+ found = True
+
+ record = data.get("records")
+
+ if record:
+ country = record.get("country_name")
+ region = record["region"].get("name") if record.get("region") else None
+ city = record.get("city")
+ postalCode = record.get("postal_code")
+ latitude = record.get("latitude")
+ longitude = record.get("longitude")
+ provider = record.get("isp")
+
+ if provider:
+ evt = SpiderFootEvent(
+ "PROVIDER_HOSTING",
+ provider,
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if latitude and longitude:
+ evt = SpiderFootEvent(
+ "PHYSICAL_COORDINATES",
+ f"{latitude}, {longitude}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if region or country or city or postalCode:
+ evt = SpiderFootEvent(
+ "GEOINFO",
+ f"Country: {country}, Region: {region}, City: {city}, Postal code: {postalCode}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ self.emitRawRirData(data, event)
+
+ def emitSkypeResolverData(self, data, event):
+ ip = data.get("ip")
+ ips = data.get("ips")
+ found = False
+
+ if ip and ip not in ips:
+ evt = SpiderFootEvent(
+ "IP_ADDRESS",
+ ip,
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if isinstance(ips, list):
+ found = True
+ for ipElem in ips:
+ if self.checkForStop():
+ return
+
+ evt = SpiderFootEvent(
+ "IP_ADDRESS",
+ ipElem.strip(),
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+
+ if found:
+ self.emitRawRirData(data, event)
+
+ def emitWafDetectorData(self, data, event):
+ firewall = data.get("result")
+
+ if firewall:
+ evt = SpiderFootEvent(
+ "WEBSERVER_TECHNOLOGY",
+ f"Firewall detected: {firewall}",
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+ self.emitRawRirData(data, event)
+
+ def emitHostname(self, data, event):
+ if not self.sf.validHost(data, self.opts['_internettlds']):
+ return
+
+ if self.opts["verify"] and not self.sf.resolveHost(data) and not self.sf.resolveHost6(data):
+ self.debug(f"Host {data} could not be resolved.")
+ if self.getTarget().matches(data):
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", data, self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ if self.getTarget().matches(data):
+ evt = SpiderFootEvent('INTERNET_NAME', data, self.__name__, event)
+ self.notifyListeners(evt)
+ if self.sf.isDomain(data, self.opts['_internettlds']):
+ evt = SpiderFootEvent('DOMAIN_NAME', data, self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ if self.cohostcount < self.opts['maxcohost']:
+ if self.opts["verify"] and not self.sf.validateIP(data, event.data):
+ self.debug("Host no longer resolves to our IP.")
+ return
+
+ if not self.opts["cohostsamedomain"]:
+ if self.getTarget().matches(data, includeParents=True):
+ self.debug(
+ f"Skipping {data} because it is on the same domain."
+ )
+ return
+
+ if self.cohostcount < self.opts["maxcohost"]:
+ evt = SpiderFootEvent("CO_HOSTED_SITE", data, self.__name__, event)
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ # Once we are in this state, return immediately.
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error("You enabled sfp_c99, but did not set an API key!")
+ self.errorState = True
+ return
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "PHONE_NUMBER":
+ phoneData = self.query("phonelookup", "number", eventData)
+ phoneData = phoneData.get("details") if phoneData else None
+
+ if phoneData:
+ self.emitPhoneData(phoneData, event)
+
+ if eventName == "DOMAIN_NAME":
+ subDomainData = self.query("subdomainfinder", "domain", eventData)
+ subDomainData = (
+ subDomainData.get("subdomains") if subDomainData is not None else None
+ )
+
+ if isinstance(subDomainData, list):
+ self.emitSubDomainData(subDomainData, event)
+
+ domainHistoryData = self.query("domainhistory", "domain", eventData)
+ domainHistoryData = (
+ domainHistoryData.get("result") if domainHistoryData else None
+ )
+
+ if isinstance(domainHistoryData, list):
+ self.emitDomainHistoryData(domainHistoryData, event)
+
+ wafDetectorData = self.query("firewalldetector", "url", eventData)
+
+ if wafDetectorData:
+ self.emitWafDetectorData(wafDetectorData, event)
+
+ if eventName == "IP_ADDRESS":
+ ipToSkypeData = self.query("ip2skype", "ip", eventData)
+
+ if ipToSkypeData:
+ self.emitIpToSkypeData(ipToSkypeData, event)
+
+ ipToDomainsData = self.query("ip2domains", "ip", eventData)
+
+ if ipToDomainsData:
+ self.emitIpToDomainsData(ipToDomainsData, event)
+
+ proxyDetectionData = self.query("proxydetector", "ip", eventData)
+
+ if proxyDetectionData:
+ self.emitProxyDetectionData(proxyDetectionData, event)
+
+ geoIPData = self.query("geoip", "host", eventData)
+
+ if geoIPData:
+ self.emitGeoIPData(geoIPData, event)
+
+ if eventName == "USERNAME":
+ skypeResolverData = self.query("skyperesolver", "username", eventData)
+
+ if skypeResolverData:
+ self.emitSkypeResolverData(skypeResolverData, event)
+
+
+# End of sfp_c99 class
diff --git a/spiderfoot/modules/sfp_callername.py b/spiderfoot/modules/sfp_callername.py
new file mode 100644
index 0000000000000000000000000000000000000000..b22377801ebd45a76903c17373d3af4251270e17
--- /dev/null
+++ b/spiderfoot/modules/sfp_callername.py
@@ -0,0 +1,136 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_callername
+# Purpose: SpiderFoot plug-in to search CallerName.com for a phone number
+# (US only) and retrieve location and reputation information.
+#
+# Author:
+#
+# Created: 2019-05-28
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_callername(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CallerName",
+ 'summary': "Lookup US phone number location and reputation information.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "http://callername.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://callername.com/faq",
+ "https://callername.com/stats"
+ ],
+ 'favIcon': "http://static.callername.com/favicon.ico",
+ 'logo': "http://static.callername.com/img/logo.min.png",
+ 'description': "CallerName is a free, reverse phone lookup service for both cell and landline numbers. "
+ "It relies on a database of white pages and business pages taken from public sources. "
+ "The easy-to-use and streamlined interface allow users to look up the caller ID information of any number quickly. "
+ "Just type the unknown number into the search bar to start. "
+ "You need not pay nor register to use this 100% free service.",
+ }
+ }
+
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['PHONE_NUMBER']
+
+ # What events this module produces
+ def producedEvents(self):
+ return ['GEOINFO', 'MALICIOUS_PHONE_NUMBER']
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Only US numbers are supported (+1)
+ if not eventData.startswith('+1'):
+ self.debug('Unsupported phone number: ' + eventData)
+ return
+
+ # Strip country code (+1) and formatting
+ number = eventData.lstrip('+1').strip('(').strip(')').strip('-').strip(' ')
+
+ if not number.isdigit():
+ self.debug('Invalid phone number: ' + number)
+ return
+
+ # Query CallerName.com for the specified phone number
+ url = f"https://callername.com/{number}"
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ self.debug('No response from CallerName.com')
+ return
+
+ if res['code'] != '200':
+ self.debug('No phone information found for ' + eventData)
+ return
+
+ location_match = re.findall(r'', str(res['content']), re.MULTILINE | re.DOTALL)
+
+ if location_match:
+ location = location_match[0]
+
+ if len(location) < 5 or len(location) > 100:
+ self.debug("Skipping likely invalid location.")
+ else:
+ evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ rep_good_match = re.findall(r'>SAFE.*?>(\d+) votes?<', str(res['content']))
+ rep_bad_match = re.findall(r'>UNSAFE.*?>(\d+) votes?<', str(res['content']))
+
+ if rep_good_match and rep_bad_match:
+ good_votes = int(rep_good_match[0])
+ bad_votes = int(rep_bad_match[0])
+
+ if bad_votes > good_votes:
+ text = f"CallerName [{eventData}]\n{url} "
+ evt = SpiderFootEvent('MALICIOUS_PHONE_NUMBER', text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_callername class
diff --git a/spiderfoot/modules/sfp_censys.py b/spiderfoot/modules/sfp_censys.py
new file mode 100644
index 0000000000000000000000000000000000000000..622a69dbfe8a6a00f680cb8808b395e22403baf9
--- /dev/null
+++ b/spiderfoot/modules/sfp_censys.py
@@ -0,0 +1,406 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_censys
+# Purpose: Query Censys.io API
+#
+# Author: Steve Micallef
+#
+# Created: 01/02/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from datetime import datetime
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_censys(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Censys",
+ 'summary': "Obtain host information from Censys.io.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://censys.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://search.censys.io/api",
+ "https://search.censys.io/search/language",
+ "https://github.com/censys/censys-postman/blob/main/Censys_Search.postman_collection.json",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://censys.io/",
+ "Register a free account",
+ "Navigate to https://censys.io/account",
+ "Click on 'API'",
+ "The API key combination is listed under 'API ID' and 'Secret'"
+ ],
+ 'favIcon': "https://censys.io/assets/favicon.png",
+ 'logo': "https://censys.io/assets/logo.png",
+ 'description': "Discover exposures and other common entry points for attackers.\n"
+ "Censys scans the entire internet constantly, including obscure ports. "
+ "We use a combination of banner grabs and deep protocol handshakes "
+ "to provide industry-leading visibility and an accurate depiction of what is live on the internet.",
+ }
+ }
+
+ opts = {
+ "censys_api_key_uid": "",
+ "censys_api_key_secret": "",
+ 'delay': 3,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxv6netblock': 120,
+ "age_limit_days": 90,
+ }
+
+ optdescs = {
+ "censys_api_key_uid": "Censys.io API UID.",
+ "censys_api_key_secret": "Censys.io API Secret.",
+ 'delay': 'Delay between requests, in seconds.',
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6netblock': "If looking up owned netblocks, the maximum IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "NETBLOCK_OWNER",
+ "NETBLOCKV6_OWNER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BGP_AS_MEMBER",
+ "UDP_PORT_OPEN",
+ "TCP_PORT_OPEN",
+ "TCP_PORT_OPEN_BANNER",
+ "OPERATING_SYSTEM",
+ "SOFTWARE_USED",
+ "WEBSERVER_HTTPHEADERS",
+ "NETBLOCK_MEMBER",
+ "NETBLOCKV6_MEMBER",
+ "GEOINFO",
+ "RAW_RIR_DATA"
+ ]
+
+ def queryHosts(self, qry):
+ secret = self.opts['censys_api_key_uid'] + ':' + self.opts['censys_api_key_secret']
+ auth = base64.b64encode(secret.encode('utf-8')).decode('utf-8')
+
+ headers = {
+ 'Authorization': f"Basic {auth}"
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://search.censys.io/api/v2/hosts/{qry}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ # API rate limit: 0.4 actions/second (120.0 per 5 minute interval)
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def queryHostsSearch(self, qry):
+ secret = self.opts['censys_api_key_uid'] + ':' + self.opts['censys_api_key_secret']
+ auth = base64.b64encode(secret.encode('utf-8')).decode('utf-8')
+
+ headers = {
+ 'Authorization': f"Basic {auth}"
+ }
+
+ params = urllib.parse.urlencode({
+ 'q': qry,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://search.censys.io/api/v2/hosts/search/?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ # API rate limit: 0.4 actions/second (120.0 per 5 minute interval)
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Censys.io.")
+ return None
+
+ if res['code'] == "400":
+ self.error("Invalid request.")
+ return None
+
+ if res['code'] == "404":
+ self.info('Censys.io returned no results')
+ return None
+
+ if res['code'] == "403":
+ self.error("Invalid API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == "429":
+ self.error("Request rate limit exceeded.")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error(f"Unexpected HTTP response code {res['code']} from Censys API.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.info('Censys.io returned no results')
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from Censys.io: {e}")
+ return None
+
+ error_type = data.get('error_type')
+ if error_type:
+ self.error(f"Censys returned an unexpected error: {error_type}")
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ eventName = event.eventType
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if self.opts['censys_api_key_uid'] == "" or self.opts['censys_api_key_secret'] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API uid/secret!")
+ self.errorState = True
+ return
+
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts['netblocklookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_OWNER':
+ max_netblock = self.opts['maxv6netblock']
+ else:
+ max_netblock = self.opts['maxnetblock']
+
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+
+ data = self.queryHosts(addr)
+
+ if not data:
+ continue
+
+ rec = data.get("result")
+
+ if not rec:
+ self.info(f"Censys.io returned no results for {addr}")
+ continue
+
+ self.debug(f"Found results for {addr} in Censys.io")
+
+ # For netblocks, we need to create the associated IP address event first.
+ if eventName == 'NETBLOCK_OWNER':
+ pevent = SpiderFootEvent("IP_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCKV6_OWNER':
+ pevent = SpiderFootEvent("IPV6_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ else:
+ pevent = event
+
+ e = SpiderFootEvent("RAW_RIR_DATA", json.dumps(rec), self.__name__, pevent)
+ self.notifyListeners(e)
+
+ try:
+ # Date format: 2021-09-22T16:46:47.623Z
+ created_dt = datetime.strptime(rec.get('last_updated_at', "1970-01-01T00:00:00.000Z"), '%Y-%m-%dT%H:%M:%S.%fZ')
+ created_ts = int(time.mktime(created_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])
+
+ if self.opts['age_limit_days'] > 0 and created_ts < age_limit_ts:
+ self.debug(f"Record found but too old ({created_dt}), skipping.")
+ continue
+ except Exception as e:
+ self.error(f"Error encountered processing last_updated_at record for {addr}: {e}")
+
+ try:
+ location = rec.get('location')
+ if location:
+ geoinfo = ', '.join(
+ [
+ _f for _f in [
+ location.get('city'),
+ location.get('province'),
+ location.get('postal_code'),
+ location.get('country'),
+ location.get('continent'),
+ ] if _f
+ ]
+ )
+ if geoinfo:
+ e = SpiderFootEvent("GEOINFO", geoinfo, self.__name__, pevent)
+ self.notifyListeners(e)
+ except Exception as e:
+ self.error(f"Error encountered processing location record for {addr}: {e}")
+
+ try:
+ services = rec.get('services')
+ if services:
+ softwares = list()
+ tcp_banners = list()
+ for service in services:
+ port = service.get('port')
+
+ if port:
+ transport_protocol = service.get('transport_protocol')
+ banner = service.get('banner')
+
+ if transport_protocol == "UDP":
+ evt = SpiderFootEvent("UDP_PORT_OPEN", f"{addr}:{port}", self.__name__, pevent)
+ self.notifyListeners(evt)
+ elif transport_protocol == "TCP":
+ evt = SpiderFootEvent("TCP_PORT_OPEN", f"{addr}:{port}", self.__name__, pevent)
+ self.notifyListeners(evt)
+ if banner:
+ tcp_banners.append(banner)
+
+ software = service.get('software', list())
+ if software:
+ for sw in software:
+ s = ' '.join(
+ filter(
+ None,
+ [
+ sw.get('vendor'),
+ sw.get('product'),
+ sw.get('version')
+ ]
+ )
+ )
+ if s:
+ softwares.append(s)
+
+ http = service.get('http')
+ if http:
+ response = http.get('response')
+ if response:
+ headers = response.get('headers')
+ if headers:
+ e = SpiderFootEvent(
+ "WEBSERVER_HTTPHEADERS",
+ json.dumps(headers, ensure_ascii=False),
+ self.__name__,
+ pevent
+ )
+ e.actualSource = addr
+ self.notifyListeners(e)
+
+ for software in set(softwares):
+ evt = SpiderFootEvent("SOFTWARE_USED", software, self.__name__, pevent)
+ self.notifyListeners(evt)
+
+ for banner in set(tcp_banners):
+ evt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", str(banner), self.__name__, pevent)
+ self.notifyListeners(evt)
+ except Exception as e:
+ self.error(f"Error encountered processing services record for {addr}: {e}")
+
+ try:
+ autonomous_system = rec.get('autonomous_system')
+ if autonomous_system:
+ asn = autonomous_system.get('asn')
+ if asn:
+ e = SpiderFootEvent("BGP_AS_MEMBER", str(asn), self.__name__, pevent)
+ self.notifyListeners(e)
+
+ bgp_prefix = autonomous_system.get('bgp_prefix')
+ if bgp_prefix and self.sf.validIpNetwork(bgp_prefix):
+ if ':' in bgp_prefix:
+ e = SpiderFootEvent("NETBLOCKV6_MEMBER", str(bgp_prefix), self.__name__, pevent)
+ else:
+ e = SpiderFootEvent("NETBLOCK_MEMBER", str(bgp_prefix), self.__name__, pevent)
+ self.notifyListeners(e)
+ except Exception as e:
+ self.error(f"Error encountered processing autonomous_system record for {addr}: {e}")
+
+ try:
+ operating_system = rec.get('operating_system')
+ if operating_system:
+ os = ' '.join(
+ filter(
+ None,
+ [
+ operating_system.get('vendor'),
+ operating_system.get('product'),
+ operating_system.get('version'),
+ operating_system.get('edition')
+ ]
+ )
+ )
+
+ if os:
+ e = SpiderFootEvent("OPERATING_SYSTEM", os, self.__name__, pevent)
+ self.notifyListeners(e)
+ except Exception as e:
+ self.error(f"Error encountered processing operating_system record for {addr}: {e}")
+
+# End of sfp_censys class
diff --git a/spiderfoot/modules/sfp_certspotter.py b/spiderfoot/modules/sfp_certspotter.py
new file mode 100644
index 0000000000000000000000000000000000000000..90ca11ca3d8faa3d8242ea5bdb517347c4684e56
--- /dev/null
+++ b/spiderfoot/modules/sfp_certspotter.py
@@ -0,0 +1,273 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_certspotter
+# Purpose: Gather information about SSL certificates from SSLMate CertSpotter API.
+#
+# Author:
+#
+# Created: 2021-08-15
+# Copyright: (c) bcoles
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_certspotter(SpiderFootPlugin):
+ meta = {
+ 'name': "CertSpotter",
+ 'summary': "Gather information about SSL certificates from SSLMate CertSpotter API.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Crawling and Scanning"],
+ 'dataSource': {
+ 'website': "https://sslmate.com/certspotter/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://sslmate.com/help/reference/ct_search_api_v1"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://sslmate.com/signup?for=ct_search_api",
+ "Register a new account with an email",
+ "Navigate to https://sslmate.com/account/",
+ "The API key is listed under 'API Credentials'",
+ ],
+ "favIcon": "https://sslmate.com/assets/@faafe50b54dfb91476c01374043f217c.png",
+ "logo": "https://sslmate.com/assets/@995de4b3fc64525a0c960b570432bcaf.png",
+ "description": "Cert Spotter monitors your domains for expiring, unauthorized, "
+ "and invalid SSL certificates, so you can act before an incident, not after."
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': '',
+ 'verify': True,
+ 'max_pages': 20,
+ 'certexpiringdays': 30
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': 'CertSpotter API key.',
+ 'verify': "Verify certificate subject alternative names resolve.",
+ 'max_pages': "Maximum number of pages of results to fetch.",
+ 'certexpiringdays': 'Number of days in the future a certificate expires to consider it as expiring.'
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['DOMAIN_NAME']
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ 'INTERNET_NAME',
+ 'INTERNET_NAME_UNRESOLVED',
+ 'DOMAIN_NAME',
+ 'CO_HOSTED_SITE',
+ 'CO_HOSTED_SITE_DOMAIN',
+ 'SSL_CERTIFICATE_ISSUED',
+ 'SSL_CERTIFICATE_ISSUER',
+ 'SSL_CERTIFICATE_MISMATCH',
+ 'SSL_CERTIFICATE_EXPIRED',
+ 'SSL_CERTIFICATE_EXPIRING',
+ 'SSL_CERTIFICATE_RAW',
+ 'RAW_RIR_DATA'
+ ]
+
+ # Query CertSpotter issuances API endpoint
+ def queryIssuances(self, domain, after=None):
+ params = {
+ 'domain': domain.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'include_subdomains': 'true',
+ 'match_wildcards': 'true',
+ 'after': (after or '')
+ }
+
+ expand = '&expand='.join(['dns_names', 'issuer', 'cert'])
+
+ headers = {
+ 'Accept': 'application/json',
+ 'Authorization': "Basic " + base64.b64encode(f"{self.opts['api_key']}:".encode('utf-8')).decode('utf-8')
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.certspotter.com/v1/issuances?{urllib.parse.urlencode(params)}&expand={expand}",
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent'],
+ )
+
+ # Free plan - 1,000 single-hostname queries / hour; 100 full-domain queries / hour
+ time.sleep(1)
+
+ if res['content'] is None:
+ self.debug('No response from CertSpotter API')
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by CertSpotter")
+ self.errorState = True
+ return None
+
+ if res['code'] != '200':
+ self.error(f"Unexpected HTTP response code {res['code']} from CertSpotter")
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ max_pages = int(self.opts['max_pages'])
+ page = 1
+ last_id = None
+ hosts = list()
+ while page <= max_pages:
+ if self.checkForStop():
+ break
+
+ if self.errorState:
+ break
+
+ data = self.queryIssuances(eventData, last_id)
+
+ if data is None or len(data) == 0:
+ break
+
+ page += 1
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for result in data:
+ cert_hosts = result.get('dns_names')
+
+ if cert_hosts:
+ for d in cert_hosts:
+ if d != eventData:
+ hosts.append(d.replace("*.", ""))
+
+ if result.get('cert') is None:
+ self.debug('Response data contains no certificate data')
+ continue
+
+ try:
+ rawcert = "-----BEGIN CERTIFICATE-----\n"
+ rawcert += result.get('cert').get('data')
+ rawcert += "\n-----END CERTIFICATE-----\n"
+ cert = self.sf.parseCert(rawcert, eventData, self.opts['certexpiringdays'])
+ except Exception as e:
+ self.info(f"Error parsing certificate: {e}")
+ continue
+
+ if not cert.get('text'):
+ self.info("Failed to parse the SSL certificate")
+ continue
+
+ evt = SpiderFootEvent('SSL_CERTIFICATE_RAW', cert['text'], self.__name__, event)
+ self.notifyListeners(evt)
+
+ if cert.get('issuer'):
+ evt = SpiderFootEvent('SSL_CERTIFICATE_ISSUER', cert['issuer'], self.__name__, event)
+ self.notifyListeners(evt)
+
+ if cert.get('issued'):
+ evt = SpiderFootEvent('SSL_CERTIFICATE_ISSUED', cert['issued'], self.__name__, event)
+ self.notifyListeners(evt)
+
+ for san in set(cert.get('altnames', list())):
+ hosts.append(san.replace("*.", ""))
+
+ if cert.get('expired'):
+ evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRED", cert.get('expirystr', 'Unknown'), self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ if cert.get('expiring'):
+ evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRING", cert.get('expirystr', 'Unknown'), self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ # "To retrieve additional issuances, take the id field of the last issuance and pass it to the issuances endpoint in the after parameter"
+ last_id = data[-1].get('id')
+
+ if last_id is None:
+ break
+
+ if not hosts:
+ return
+
+ if self.opts['verify']:
+ self.info(f"Resolving {len(set(hosts))} hostnames ...")
+
+ for domain in set(hosts):
+ if self.checkForStop():
+ return
+
+ if domain in self.results:
+ continue
+
+ if self.getTarget().matches(domain, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ if self.opts['verify'] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt_type += '_UNRESOLVED'
+ else:
+ evt_type = 'CO_HOSTED_SITE'
+
+ evt = SpiderFootEvent(evt_type, domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(domain, self.opts['_internettlds']):
+ if evt_type == 'CO_HOSTED_SITE':
+ evt = SpiderFootEvent('CO_HOSTED_SITE_DOMAIN', domain, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent('DOMAIN_NAME', domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_certspotter class
diff --git a/spiderfoot/modules/sfp_cinsscore.py b/spiderfoot/modules/sfp_cinsscore.py
new file mode 100644
index 0000000000000000000000000000000000000000..320a6bdbff281a5cf60f458d06addc30a7da6b57
--- /dev/null
+++ b/spiderfoot/modules/sfp_cinsscore.py
@@ -0,0 +1,181 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cinsscore
+# Purpose: Checks if an IP address is malicious according to the CINS Army list.
+#
+# Author: steve@binarypool.com
+#
+# Created: 13/05/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cinsscore(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CINS Army List",
+ 'summary': "Check if a netblock or IP address is malicious according to Collective Intelligence Network Security (CINS) Army list.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://cinsscore.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'favIcon': 'https://cinsscore.com/media/images/fav-icon.png',
+ 'logo': 'https://cinsscore.com/media/images/logo-small-grey-inset.png',
+ 'description': "Leveraging data from our network of Sentinel "
+ "devices and other trusted InfoSec sources, CINS is a "
+ "Threat Intelligence database that provides an accurate "
+ "and timely score for any IP address in the world."
+ "The CINS Army list is a subset of the CINS Active Threat Intelligence ruleset.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliate IP addresses?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "NETBLOCK_MEMBER",
+ "NETBLOCK_OWNER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_NETBLOCK",
+ ]
+
+ def query(self, qry, targetType):
+ cid = "_cinsscore"
+ url = "https://cinsscore.com/list/ci-badguys.txt"
+
+ data = dict()
+ data["content"] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))
+
+ if data["content"] is None:
+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if data["code"] != "200":
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ if data["content"] is None:
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("sfmal_" + cid, data['content'])
+
+ for line in data["content"].split('\n'):
+ ip = line.strip().lower()
+
+ if targetType == "netblock":
+ try:
+ if IPAddress(ip) in IPNetwork(qry):
+ self.debug(f"{ip} found within netblock/subnet {qry} in cinsscore.com list.")
+ return url
+ except Exception as e:
+ self.debug(f"Error encountered parsing: {e}")
+ continue
+
+ if targetType == "ip":
+ if qry.lower() == ip:
+ self.debug(f"{qry} found in cinsscore.com list.")
+ return url
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} with cinsscore.com")
+
+ url = self.query(eventData, targetType)
+
+ if not url:
+ return
+
+ text = f"cinsscore.com [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_cinsscore class
diff --git a/spiderfoot/modules/sfp_circllu.py b/spiderfoot/modules/sfp_circllu.py
new file mode 100644
index 0000000000000000000000000000000000000000..19a923e356d43c1655d5364adeab85a11faa3289
--- /dev/null
+++ b/spiderfoot/modules/sfp_circllu.py
@@ -0,0 +1,245 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_circllu
+# Purpose: Query circl.lu using their API
+#
+# Author: Steve Micallef
+#
+# Created: 16/02/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import json
+import re
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_circllu(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CIRCL.LU",
+ 'summary': "Obtain information from CIRCL.LU's Passive DNS and Passive SSL databases.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.circl.lu/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://www.circl.lu/services/passive-dns/",
+ "https://www.circl.lu/services/passive-ssl/",
+ "https://www.circl.lu/services/",
+ "https://www.circl.lu/pub/",
+ "https://www.circl.lu/projects"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.circl.lu/contact/",
+ "Contact with email or phone to request access for Passive DNS and Passive SSL API services",
+ "The API access will be provided once approved"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://www.circl.lu/",
+ 'logo': "https://www.circl.lu/assets/images/circl-logo.png",
+ 'description': "The Computer Incident Response Center Luxembourg (CIRCL) is a government-driven initiative "
+ "designed to gather, review, report and respond to computer security threats and incidents.\n"
+ "CIRCL provides a reliable and trusted point of contact for any users, companies and organizations "
+ "based in Luxembourg, for the handling of attacks and incidents. "
+ "Its team of experts acts like a fire brigade, with the ability to react promptly and "
+ "efficiently whenever threats are suspected, detected or incidents occur.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key_login": "",
+ "api_key_password": "",
+ "age_limit_days": 0,
+ "verify": True,
+ "cohostsamedomain": False,
+ "maxcohost": 100
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key_login": "CIRCL.LU login.",
+ "api_key_password": "CIRCL.LU password.",
+ "age_limit_days": "Ignore any Passive DNS records older than this many days. 0 = unlimited.",
+ "verify": "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ "cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME", "NETBLOCK_OWNER", "IP_ADDRESS", "DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["IP_ADDRESS", "SSL_CERTIFICATE_ISSUED", "CO_HOSTED_SITE"]
+
+ def query(self, qry, qtype):
+ if self.errorState:
+ return None
+
+ if qtype == "PDNS":
+ url = "https://www.circl.lu/pdns/query/" + qry
+ else:
+ url = "https://www.circl.lu/v2pssl/query/" + qry
+
+ secret = self.opts['api_key_login'] + ':' + self.opts['api_key_password']
+ b64_val = base64.b64encode(secret.encode('utf-8'))
+ headers = {
+ 'Authorization': f"Basic {b64_val.decode('utf-8')}"
+ }
+
+ # Be more forgiving with the timeout as some queries for subnets can be slow
+ res = self.sf.fetchUrl(url, timeout=30,
+ useragent="SpiderFoot", headers=headers)
+
+ if res['code'] not in ["200", "201"]:
+ self.error("CIRCL.LU access seems to have been rejected or you have exceeded usage limits.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.info("No CIRCL.LU info found for " + qry)
+ return None
+
+ return res['content']
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ ret = None
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Ignore messages from myself
+ if srcModuleName == "sfp_circllu":
+ self.debug("Ignoring " + eventName + ", from self.")
+ return
+
+ if self.opts['api_key_login'] == "" or self.opts['api_key_password'] == "":
+ self.error("You enabled sfp_circllu but did not set an credentials!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['IP_ADDRESS', 'NETBLOCK_OWNER']:
+ # CIRCL.LU limit the maximum subnet size to 23
+ # http://circl.lu/services/passive-ssl/
+ if "/" in eventData:
+ addr, mask = eventData.split("/")
+ if int(mask) < 23:
+ self.debug("Network size bigger than permitted by CIRCL.LU.")
+ else:
+ ret = self.query(eventData, "PSSL")
+ if not ret:
+ self.info("No CIRCL.LU passive SSL data found for " + eventData)
+ else:
+ ret = self.query(eventData, "PSSL")
+ if not ret:
+ self.info("No CIRCL.LU passive SSL data found for " + eventData)
+
+ if ret:
+ try:
+ # Generate an event for the IP first, and then link the cert
+ # to that event.
+ j = json.loads(ret)
+ for ip in j:
+ ipe = event
+ if ip != eventData:
+ ipe = SpiderFootEvent("IP_ADDRESS", ip, self.__name__, event)
+ self.notifyListeners(ipe)
+ for crt in j[ip]['subjects']:
+ r = re.findall(r".*[\"\'](.+CN=([a-zA-Z0-9\-\*\.])+)[\"\'].*",
+ str(j[ip]['subjects'][crt]), re.IGNORECASE)
+ if r:
+ e = SpiderFootEvent("SSL_CERTIFICATE_ISSUED", r[0][0], self.__name__, ipe)
+ self.notifyListeners(e)
+ except Exception as e:
+ self.error("Invalid response returned from CIRCL.LU: " + str(e))
+
+ if eventName in ['IP_ADDRESS', 'INTERNET_NAME', 'DOMAIN_NAME']:
+ ret = self.query(eventData, "PDNS")
+ if not ret:
+ self.info("No CIRCL.LU passive DNS data found for " + eventData)
+ return
+
+ # CIRCL.LU doesn't return valid JSON - it's one JSON record per line
+ for line in ret.split("\n"):
+ if len(line) < 2:
+ continue
+ try:
+ rec = json.loads(line)
+ except Exception as e:
+ self.error("Invalid response returned from CIRCL.LU: " + str(e))
+ continue
+
+ age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])
+ if self.opts['age_limit_days'] > 0 and rec['time_last'] < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ continue
+
+ cohosts = list()
+ if eventName == "IP_ADDRESS":
+ # Record could be pointing to our IP, or from our IP
+ if rec['rrtype'] == "A" and rec['rdata'] == eventData:
+ if not self.getTarget().matches(rec['rrname']):
+ # We found a co-host
+ cohosts.append(rec['rrname'])
+
+ if eventName in ["INTERNET_NAME", "DOMAIN_NAME"]:
+ # Record could be an A/CNAME of this entity, or something pointing to it
+ if rec['rdata'] == eventData:
+ if not self.getTarget().matches(rec['rrname']):
+ # We found a co-host
+ cohosts.append(rec['rrname'])
+
+ for co in cohosts:
+ if eventName == "IP_ADDRESS" and (self.opts['verify'] and not self.sf.validateIP(co, eventData)):
+ self.debug("Host no longer resolves to our IP.")
+ continue
+
+ if not self.opts['cohostsamedomain']:
+ if self.getTarget().matches(co, includeParents=True):
+ self.debug("Skipping " + co + " because it is on the same domain.")
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ e = SpiderFootEvent("CO_HOSTED_SITE", co, self.__name__, event)
+ self.notifyListeners(e)
+ self.cohostcount += 1
+
+# End of sfp_circllu class
diff --git a/spiderfoot/modules/sfp_citadel.py b/spiderfoot/modules/sfp_citadel.py
new file mode 100644
index 0000000000000000000000000000000000000000..7720d6aebb5b0b3e05ed33c92a45b7c6a31f71e2
--- /dev/null
+++ b/spiderfoot/modules/sfp_citadel.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_citadel
+# Purpose: SpiderFoot plug-in to search Leak-Lookup using their API,
+# for potential data breaches.
+#
+# Author: sn
+#
+# Created: 15/08/2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_citadel(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Leak-Lookup",
+ 'summary': "Searches Leak-Lookup.com's database of breaches.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "https://leak-lookup.com/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://leak-lookup.com/api",
+ "https://leak-lookup.com/databases"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://leak-lookup.com",
+ "Register an account",
+ "Login to your account",
+ "Click on 'Account'",
+ "Click on 'API'",
+ "The API key is listed under 'API Key'"
+ ],
+ 'favIcon': "https://leak-lookup.com/favicon.png",
+ 'logo': "https://leak-lookup.com/favicon.png",
+ 'description': "Leak-Lookup allows you to search across thousands of data breaches "
+ "to stay on top of credentials that may have been compromised in the wild.\n"
+ "The creators came together when they realized they had a vast trove of data "
+ "that could be of great value to pen-testers seeking weaknesses in client passwords "
+ "and those concerned about which of their credentials have been leaked into the wild.\n"
+ "Always looking forward, Leak-Lookup invests all of its profits back into securing the "
+ "latest data breaches and leaks / dumps as they become available, ensuring that "
+ "as well as historical data, Leak-Lookup becomes a field leader in credential monitoring.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "timeout": 60
+ }
+ optdescs = {
+ "api_key": "Leak-Lookup API key. Without this you're limited to the public API.",
+ "timeout": "Custom timeout due to heavy traffic at times."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+ self.__dataSource__ = "Leak-Lookup.com"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['EMAILADDR']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["EMAILADDR_COMPROMISED"]
+
+ # Query email address
+ # https://leak-lookup.com/api
+ def queryEmail(self, email):
+ apikey = self.opts['api_key']
+
+ if not apikey:
+ # Public API key
+ apikey = "3edfb5603418f101926c64ca5dd0e409"
+
+ params = {
+ 'query': email.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'type': 'email_address',
+ 'key': apikey
+ }
+
+ res = self.sf.fetchUrl("https://leak-lookup.com/api/search",
+ postData=urllib.parse.urlencode(params),
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['code'] == "429":
+ time.sleep(10)
+ return self.queryEmail(email)
+
+ if res['content'] is None:
+ self.debug('No response from Leak-Lookup.com')
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.queryEmail(eventData)
+
+ if data is None:
+ return
+
+ error = data.get('error')
+ message = data.get('message')
+
+ if error == 'true':
+ self.error(f"Error encountered processing {eventData}: {message}")
+ if "MISSING API" in message:
+ self.errorState = True
+ return
+ return
+
+ if not message:
+ return
+
+ for site in message:
+ self.info(f"Found Leak-Lookup entry for {eventData}: {site}")
+ evt = SpiderFootEvent("EMAILADDR_COMPROMISED", f"{eventData} [{site}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_citadel class
diff --git a/spiderfoot/modules/sfp_cleanbrowsing.py b/spiderfoot/modules/sfp_cleanbrowsing.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f7ef8c86fc39e795af3453ed07679590f72baeb
--- /dev/null
+++ b/spiderfoot/modules/sfp_cleanbrowsing.py
@@ -0,0 +1,200 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cleanbrowsing
+# Purpose: SpiderFoot plug-in for looking up whether hosts are blocked by
+# CleanBrowsing.org DNS content family filters
+# (185.228.168.168 and 185.228.168.169).
+#
+# Author: Steve Micallef
+#
+# Created: 30/05/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cleanbrowsing(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CleanBrowsing.org",
+ 'summary': "Check if a host would be blocked by CleanBrowsing.org DNS content filters.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://cleanbrowsing.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://cleanbrowsing.org/guides/",
+ "https://cleanbrowsing.org/filters/",
+ "https://cleanbrowsing.org/how-it-works",
+ "https://cleanbrowsing.org/web-filtering-for-shools-and-cipa-compliance",
+ "https://cleanbrowsing.org/getting-started"
+ ],
+ 'favIcon': "https://cleanbrowsing.org/favicon-new.ico",
+ 'logo': "https://cleanbrowsing.org/images/logos/CleanBrowsing-logo-large-2019-Orange-II.png",
+ 'description': "You get to decide what type of content is allowed in your home or network via our "
+ "DNS-based content filtering service. Parents can protect their kids from adult content, "
+ "schools can be CIPA compliant and businesses can block malicious domains and "
+ "gain visibility into their network.\n"
+ "CleanBrowsing is a DNS-based content filtering service that offers a safe way to browse the web without surprises. "
+ "It intercepts domain requests and filter sites that should be blocked, based on your requirements. "
+ "Our free family filter, for example, blocks adult content, while still allowing Google, "
+ "Youtube, Bing, DuckDuckGo and the rest of the web to load safely.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryFamilyDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["185.228.168.168", "185.228.168.169"]
+
+ try:
+ addrs = res.resolve(qaddr)
+ self.debug(f"Addresses returned: {addrs}")
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+ return False
+
+ if addrs:
+ return True
+ return False
+
+ def queryAdultDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["185.228.168.10", "185.228.169.11"]
+
+ try:
+ addrs = res.resolve(qaddr)
+ self.debug(f"Addresses returned: {addrs}")
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+ return False
+
+ if addrs:
+ return True
+ return False
+
+ def querySecurityDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["185.228.168.9", "185.228.169.9"]
+
+ try:
+ addrs = res.resolve(qaddr)
+ self.debug(f"Addresses returned: {addrs}")
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+ return False
+
+ if addrs:
+ return True
+ return False
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ # Check that it resolves first, as it becomes a valid
+ # malicious host only if NOT resolved by CleanBrowsing DNS.
+ if not self.sf.resolveHost(eventData) and not self.sf.resolveHost6(eventData):
+ return
+
+ family = self.queryFamilyDNS(eventData)
+ adult = self.queryAdultDNS(eventData)
+ security = self.querySecurityDNS(eventData)
+
+ # Host was found, not blocked
+ if family and adult and security:
+ return
+
+ self.debug(f"{eventData} was blocked by CleanBrowsing DNS")
+
+ if not security:
+ evt = SpiderFootEvent(
+ blacklist_type,
+ f"CleanBrowsing DNS - Security [{eventData}]",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(
+ malicious_type,
+ f"CleanBrowsing DNS - Security [{eventData}]",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+ elif not adult:
+ evt = SpiderFootEvent(
+ blacklist_type,
+ f"CleanBrowsing DNS - Adult [{eventData}]",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+ elif not family:
+ evt = SpiderFootEvent(
+ blacklist_type,
+ f"CleanBrowsing DNS - Family [{eventData}]",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_cleanbrowsing class
diff --git a/spiderfoot/modules/sfp_cleantalk.py b/spiderfoot/modules/sfp_cleantalk.py
new file mode 100644
index 0000000000000000000000000000000000000000..a13c699ae7d3eb158e831f9fb2c7d4e703bf2d0e
--- /dev/null
+++ b/spiderfoot/modules/sfp_cleantalk.py
@@ -0,0 +1,197 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cleantalk
+# Purpose: Checks if a netblock or IP address is on CleanTalk.org's spam IP list.
+#
+# Author: steve@binarypool.com
+#
+# Created: 05/08/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cleantalk(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CleanTalk Spam List",
+ 'summary': "Check if a netblock or IP address is on CleanTalk.org's spam IP list.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://cleantalk.org",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://cleantalk.org/help",
+ "https://cleantalk.org/help/introduction",
+ "https://cleantalk.org/help/api-spam-check",
+ "https://cleantalk.org/wordpress-security-malware-firewall",
+ "https://cleantalk.org/price-anti-spam",
+ "https://cleantalk.org/ssl-certificates/cheap-positivessl-certificate",
+ "https://cleantalk.org/email-checker",
+ "https://cleantalk.org/blacklists"
+ ],
+ 'favIcon': "https://cleantalk.org/favicons/favicon-16x16.png",
+ 'logo': "https://cleantalk.org/favicons/favicon-16x16.png",
+ 'description': "CleanTalk is a Cloud-Based spam filtering service that allows you to protect your website from spam. "
+ "CleanTalk provides spam protection that invisible to visitors "
+ "without using captcha or other methods when visitors have to prove that they are real people.\n"
+ "CleanTalk provides cloud anti-spam solutions for CMS and we developed plugins for the most of popular "
+ "CMS: WordPress anti-spam plugin, Joomla anti-spam plugin, Drupal and etc. "
+ "With our simple cloud spam checker, you can be sure your website is protected from spam bots, spam comments, and users.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliate IP addresses?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'AFFILIATE_IPADDR',
+ 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER'
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ ]
+
+ def query(self, qry, targetType):
+ cid = "_cleantalk"
+ url = "https://iplists.firehol.org/files/cleantalk_7d.ipset"
+
+ data = dict()
+ data["content"] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))
+
+ if data["content"] is None:
+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if data["code"] != "200":
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ if data["content"] is None:
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("sfmal_" + cid, data['content'])
+
+ for line in data["content"].split('\n'):
+ ip = line.strip().lower()
+
+ if ip.startswith('#'):
+ continue
+
+ if targetType == "netblock":
+ try:
+ if IPAddress(ip) in IPNetwork(qry):
+ self.debug(f"{ip} found within netblock/subnet {qry} in CleanTalk Spam List.")
+ return url
+ except Exception as e:
+ self.debug(f"Error encountered parsing: {e}")
+ continue
+
+ if targetType == "ip":
+ if qry.lower() == ip:
+ self.debug(f"{qry} found in CleanTalk Spam List.")
+ return url
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} with CleanTalk Spam List")
+
+ url = self.query(eventData, targetType)
+
+ if not url:
+ return
+
+ self.debug(f"{eventData} found in Cleantalk Spam List")
+
+ text = f"CleanTalk Spam List [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_cleantalk class
diff --git a/spiderfoot/modules/sfp_clearbit.py b/spiderfoot/modules/sfp_clearbit.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6a577673da21bb8a4bddb956ba3f0dbc0d14873
--- /dev/null
+++ b/spiderfoot/modules/sfp_clearbit.py
@@ -0,0 +1,286 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_clearbit
+# Purpose: Query clearbit.com using their API.
+#
+# Author: Steve Micallef
+#
+# Created: 20/03/2017
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import urllib.error
+import urllib.parse
+import urllib.request
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_clearbit(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Clearbit",
+ 'summary': "Check for names, addresses, domains and more based on lookups of e-mail addresses on clearbit.com.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://clearbit.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://clearbit.com/docs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://clearbit.com",
+ "Register account for a Free Trial",
+ "Navigate to https://dashboard.clearbit.com/api",
+ "The API key is listed under 'Your API Key'"
+ ],
+ 'favIcon': "https://clearbit.com/assets/site/logo.png",
+ 'logo': "https://clearbit.com/assets/site/logo.png",
+ 'description': "Clearbit is the marketing data engine for all of your customer interactions. "
+ "Deeply understand your customers, identify future prospects, "
+ "and personalize every single marketing and sales interaction.\n"
+ "Rely on fresh, accurate data with our proprietary real-time lookups. "
+ "Then act on new information immediately, with sales alerting and job change notifications.\n"
+ "Get company attributes like employee count, technologies used, and industry classification—and "
+ "get employee details like role, seniority, and even job change notifications, right at your fingertips.\n"
+ "With our dataset and machine learning algorithms, you’ll have all of "
+ "the information you need to convert leads and grow your business.",
+ }
+ }
+
+ opts = {
+ "api_key": ""
+ }
+
+ optdescs = {
+ "api_key": "Clearbit.com API key."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["EMAILADDR"]
+
+ def producedEvents(self):
+ return [
+ "RAW_RIR_DATA",
+ "PHONE_NUMBER",
+ "PHYSICAL_ADDRESS",
+ "AFFILIATE_INTERNET_NAME",
+ "EMAILADDR",
+ "EMAILADDR_GENERIC",
+ "INTERNET_NAME"
+ ]
+
+ def query(self, email: str):
+ api_key = self.opts['api_key']
+
+ if isinstance(api_key, str):
+ api_key = api_key.encode('utf-8')
+
+ token = base64.b64encode(api_key + ':'.encode('utf-8'))
+ headers = {
+ 'Accept': 'application/json',
+ 'Authorization': "Basic " + token.decode('utf-8')
+ }
+ params = {
+ 'email': email
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://person.clearbit.com/v2/combined/find?{urllib.parse.urlencode(params)}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Clearbit.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results from Clearbit.")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid Clearbit API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == "402":
+ self.error("You have exceeded your Clearbit API request quota.")
+ self.errorState = True
+ return None
+
+ # Rate limit is 600 requests per minute
+ # https://dashboard.clearbit.com/docs#rate-limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by Clearbit.")
+ return None
+
+ if res['code'] == '500' or res['code'] == '502' or res['code'] == '503':
+ self.error("Clearbit service is unavailable.")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error(f"Unexpected reply from Clearbit: {res['code']}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from Clearbit: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+ if not data:
+ return
+
+ try:
+ # Get the name associated with the e-mail
+ person = data.get('person')
+ if person:
+ name = person.get('name')
+ if name:
+ fullName = name.get('fullName')
+ if fullName:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA",
+ f"Possible full name: {fullName}",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+ except Exception:
+ self.debug("Unable to extract person name from JSON.")
+ pass
+
+ # Get the location of the person, also indicating
+ # the location of the employer.
+ try:
+ geo = data.get('geo')
+ if geo:
+ location = ', '.join(
+ filter(
+ None,
+ [
+ geo.get('streetNumber'),
+ geo.get('streetName'),
+ geo.get('city'),
+ geo.get('postalCode'),
+ geo.get('state'),
+ geo.get('country')
+ ]
+ )
+ )
+
+ if location:
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
+ except Exception:
+ self.debug("Unable to extract location from JSON.")
+ pass
+
+ try:
+ company = data.get('company')
+ if company:
+ domainAliases = company.get('domainAliases')
+ if domainAliases:
+ for d in domainAliases:
+ if self.getTarget().matches(d):
+ t = "INTERNET_NAME"
+ else:
+ t = "AFFILIATE_INTERNET_NAME"
+ evt = SpiderFootEvent(
+ t,
+ d,
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ site = company.get('site')
+ if site:
+ if 'phoneNumbers' in site:
+ for p in site['phoneNumbers']:
+ evt = SpiderFootEvent("PHONE_NUMBER", p, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if 'emailAddresses' in company['site']:
+ for e in site['emailAddresses']:
+ if e.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+ evt = SpiderFootEvent(evttype, e, self.__name__, event)
+ self.notifyListeners(evt)
+
+ # Get the location of the person, also indicating
+ # the location of the employer.
+ company_geo = company.get('geo')
+ if company_geo:
+ location = ', '.join(
+ filter(
+ None,
+ [
+ company_geo.get('streetNumber'),
+ company_geo.get('streetName'),
+ company_geo.get('city'),
+ company_geo.get('postalCode'),
+ company_geo.get('state'),
+ company_geo.get('country')
+ ]
+ )
+ )
+
+ if location:
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
+ except Exception:
+ self.debug("Unable to extract company info from JSON.")
+ pass
+
+# End of sfp_clearbit class
diff --git a/spiderfoot/modules/sfp_cloudflaredns.py b/spiderfoot/modules/sfp_cloudflaredns.py
new file mode 100644
index 0000000000000000000000000000000000000000..47a06cbe5e497fbc7be8c2d16b7c5f7e085980ad
--- /dev/null
+++ b/spiderfoot/modules/sfp_cloudflaredns.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cloudflaredns
+# Purpose: SpiderFoot plug-in for looking up whether hosts are blocked by
+# CloudFlare family and malware filtering DNS servers.
+#
+# Author: Steve Micallef
+#
+# Created: 11/05/2020
+# Copyright: (c) Steve Micallef 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cloudflaredns(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CloudFlare DNS",
+ 'summary': "Check if a host would be blocked by CloudFlare DNS.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.cloudflare.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://developers.cloudflare.com/1.1.1.1/1.1.1.1-for-families/"
+ ],
+ 'favIcon': "https://www.cloudflare.com/img/favicon/favicon-32x32.png",
+ 'logo': "https://www.cloudflare.com/img/logo-web-badges/cf-logo-on-white-bg.svg",
+ 'description': "1.1.1.1 for Families is the easiest way to add a layer of protection to "
+ "your home network and protect it from malware and adult content. "
+ "1.1.1.1 for Families leverages Cloudflare’s global network to ensure "
+ "that it is fast and secure around the world.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryFamilyDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["1.1.1.3", "1.0.0.3"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def queryMalwareDNS(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["1.1.1.2", "1.0.0.2"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ e = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ e = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ e = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ family = self.sf.normalizeDNS(self.queryFamilyDNS(eventData))
+ malware = self.sf.normalizeDNS(self.queryMalwareDNS(eventData))
+
+ if not family or not malware:
+ return
+
+ if '0.0.0.0' not in family and '0.0.0.0' not in malware:
+ return
+
+ # Host is blocked only by family filters
+ if '0.0.0.0' not in malware:
+ self.debug(f"{eventData} blocked by CloudFlare Family DNS")
+ evt = SpiderFootEvent(e, f"CloudFlare - Family [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ # Host is blocked only by malware filters
+ self.debug(f"{eventData} blocked by CloudFlare Malware DNS")
+ evt = SpiderFootEvent(e, f"CloudFlare - Malware [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == "INTERNET_NAME":
+ e = "MALICIOUS_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ e = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ e = "MALICIOUS_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+
+ evt = SpiderFootEvent(e, f"CloudFlare - Malware [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_cloudflaredns class
diff --git a/spiderfoot/modules/sfp_coinblocker.py b/spiderfoot/modules/sfp_coinblocker.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dda09065162dc3d470929f28b66918e18ec2ec2
--- /dev/null
+++ b/spiderfoot/modules/sfp_coinblocker.py
@@ -0,0 +1,196 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_coinblocker
+# Purpose: Checks if a hostname is listed on CoinBlockerLists.
+#
+# Author: steve@binarypool.com
+#
+# Created: 07/09/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_coinblocker(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CoinBlocker Lists",
+ 'summary': "Check if a domain appears on CoinBlocker lists.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://zerodot1.gitlab.io/CoinBlockerListsWeb/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://zerodot1.gitlab.io/CoinBlockerListsWeb/downloads.html",
+ "https://zerodot1.gitlab.io/CoinBlockerListsWeb/references.html",
+ "https://zerodot1.gitlab.io/CoinBlockerListsWeb/aboutthisproject.html"
+ ],
+ 'favIcon': "https://zerodot1.gitlab.io/CoinBlockerListsWeb/assets/img/favicon.png",
+ 'logo': "https://zerodot1.gitlab.io/CoinBlockerListsWeb/assets/img/favicon.png",
+ 'description': "The CoinBlockerLists are a project to prevent illegal mining in "
+ "browsers or other applications using IPlists and URLLists.\n"
+ "It's not just to block everything without any reason, but to protect "
+ "Internet users from illegal mining.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'cacheperiod': 18,
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryBlocklist(self, target):
+ blocklist = self.retrieveBlocklist()
+
+ if not blocklist:
+ return False
+
+ if target.lower() in blocklist:
+ self.debug(f"Host name {target} found in CoinBlocker list.")
+ return True
+
+ return False
+
+ def retrieveBlocklist(self):
+ blocklist = self.sf.cacheGet('coinblocker', self.opts.get('cacheperiod', 24))
+
+ if blocklist is not None:
+ return self.parseBlocklist(blocklist)
+
+ url = "https://zerodot1.gitlab.io/CoinBlockerLists/list.txt"
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from {url}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error(f"Received no content from {url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("coinblocker", res['content'])
+
+ return self.parseBlocklist(res['content'])
+
+ def parseBlocklist(self, blocklist):
+ """Parse plaintext CoinBlocker list
+
+ Args:
+ blocklist (str): plaintext CoinBlocker list
+
+ Returns:
+ list: list of blocked host names
+ """
+ hosts = list()
+
+ if not blocklist:
+ return hosts
+
+ for line in blocklist.split('\n'):
+ if not line:
+ continue
+ if line.startswith('#'):
+ continue
+ host = line.strip()
+ # Note: Validation with sf.validHost() is too slow to use here
+ # if not self.sf.validHost(host, self.opts['_internettlds']):
+ # continue
+ if not host:
+ continue
+ hosts.append(host.lower())
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with CoinBlocker list")
+
+ if not self.queryBlocklist(eventData):
+ return
+
+ url = "https://zerodot1.gitlab.io/CoinBlockerLists/list.txt"
+ text = f"CoinBlocker [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_coinblocker class
diff --git a/spiderfoot/modules/sfp_commoncrawl.py b/spiderfoot/modules/sfp_commoncrawl.py
new file mode 100644
index 0000000000000000000000000000000000000000..451a71a2c206a71fc63964fc338682eb60079cba
--- /dev/null
+++ b/spiderfoot/modules/sfp_commoncrawl.py
@@ -0,0 +1,192 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_commoncrawl
+# Purpose: Searches the commoncrawl.org project's indexes for URLs related
+# to the target.
+#
+# Author: Steve Micallef
+#
+# Created: 05/09/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_commoncrawl(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CommonCrawl",
+ 'summary': "Searches for URLs found through CommonCrawl.org.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "http://commoncrawl.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://commoncrawl.org/the-data/get-started/",
+ "https://commoncrawl.org/the-data/examples/",
+ "https://commoncrawl.org/the-data/tutorials/"
+ ],
+ 'favIcon': "https://commoncrawl.org/wp-content/themes/commoncrawl/img/favicon.png",
+ 'logo': "https://commoncrawl.org/wp-content/themes/commoncrawl/img/favicon.png",
+ 'description': "We build and maintain an open repository of web crawl data that can be accessed and analyzed by anyone.\n"
+ "Everyone should have the opportunity to indulge their curiosities, analyze the world and pursue brilliant ideas. "
+ "Small startups or even individuals can now access high quality crawl data that was previously "
+ "only available to large search engine corporations.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "indexes": 6
+ }
+
+ # Option descriptions
+ optdescs = {
+ "indexes": "Number of most recent indexes to attempt, because results tend to be occasionally patchy."
+ }
+
+ results = None
+ indexBase = list()
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.indexBase = list()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def search(self, target):
+ ret = list()
+ for index in self.indexBase:
+ url = f"https://index.commoncrawl.org/{index}-index?url={target}/*&output=json"
+ res = self.sf.fetchUrl(url, timeout=60,
+ useragent="SpiderFoot")
+
+ if res['code'] in ["400", "401", "402", "403", "404"]:
+ self.error("CommonCrawl search doesn't seem to be available.")
+ self.errorState = True
+ return None
+
+ if not res['content']:
+ self.error("CommonCrawl search doesn't seem to be available.")
+ self.errorState = True
+ return None
+
+ ret.append(res['content'])
+
+ return ret
+
+ def getLatestIndexes(self):
+ url = "https://index.commoncrawl.org/"
+ res = self.sf.fetchUrl(url, timeout=60,
+ useragent="SpiderFoot")
+
+ if res['code'] in ["400", "401", "402", "403", "404"]:
+ self.error("CommonCrawl index collection doesn't seem to be available.")
+ self.errorState = True
+ return list()
+
+ if not res['content']:
+ self.error("CommonCrawl index collection doesn't seem to be available.")
+ self.errorState = True
+ return list()
+
+ indexes = re.findall(r".*(CC-MAIN-\d+-\d+).*", str(res['content']))
+ indexlist = dict()
+ for m in indexes:
+ ms = m.replace("CC-MAIN-", "").replace("-", "")
+ indexlist[ms] = True
+
+ topindexes = sorted(list(indexlist.keys()), reverse=True)[0:self.opts['indexes']]
+
+ if len(topindexes) < self.opts['indexes']:
+ self.error("Not able to find latest CommonCrawl indexes.")
+ self.errorState = True
+ return list()
+
+ retindex = list()
+ for i in topindexes:
+ retindex.append("CC-MAIN-" + str(i)[0:4] + "-" + str(i)[4:6])
+ self.debug("CommonCrawl indexes: " + str(retindex))
+ return retindex
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["LINKED_URL_INTERNAL"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if len(self.indexBase) == 0:
+ self.indexBase = self.getLatestIndexes()
+
+ if not self.indexBase:
+ self.error("Unable to fetch CommonCrawl index.")
+ return
+
+ if len(self.indexBase) == 0:
+ self.error("Unable to fetch CommonCrawl index.")
+ return
+
+ data = self.search(eventData)
+ if not data:
+ self.error("Unable to obtain content from CommonCrawl.")
+ return
+
+ sent = list()
+ for content in data:
+ try:
+ for line in content.split("\n"):
+ if self.checkForStop():
+ return
+
+ if len(line) < 2:
+ continue
+ link = json.loads(line)
+ if 'url' not in link:
+ continue
+
+ # CommonCrawl sometimes returns hosts with a trailing . after the domain
+ link['url'] = link['url'].replace(eventData + ".", eventData)
+
+ if link['url'] in sent:
+ continue
+ sent.append(link['url'])
+
+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link['url'],
+ self.__name__, event)
+ self.notifyListeners(evt)
+ except Exception as e:
+ self.error("Malformed JSON from CommonCrawl.org: " + str(e))
+ return
+
+# End of sfp_commoncrawl class
diff --git a/spiderfoot/modules/sfp_comodo.py b/spiderfoot/modules/sfp_comodo.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ee0199daf51ad98bd3130c89109304aa3688a65
--- /dev/null
+++ b/spiderfoot/modules/sfp_comodo.py
@@ -0,0 +1,133 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_comodo
+# Purpose: SpiderFoot plug-in for looking up whether hosts are blocked by
+# Comodo Secure DNS.
+#
+# Author: Steve Micallef
+#
+# Created: 30/05/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_comodo(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Comodo Secure DNS",
+ 'summary': "Check if a host would be blocked by Comodo Secure DNS.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.comodo.com/secure-dns/",
+ 'model': "FREE_NOAUTH_LIMITED",
+ 'references': [
+ "https://cdome.comodo.com/pdf/Datasheet-Dome-Shield.pdf",
+ "http://securedns.dnsbycomodo.com/",
+ "https://www.comodo.com/secure-dns/secure-dns-assets/dowloads/ccs-dome-shield-whitepaper-threat-intelligence.pdf",
+ "https://www.comodo.com/secure-dns/secure-dns-assets/dowloads/domeshield-all-use-cases.pdf",
+ ],
+ 'favIcon': "https://www.comodo.com/favicon.ico",
+ 'logo': "https://www.comodo.com/new-assets/images/logo.png",
+ 'description': "Comodo Secure DNS is a domain name resolution service "
+ "that resolves your DNS requests through our worldwide network of redundant DNS servers, "
+ "bringing you the most reliable fully redundant DNS service anywhere, for a safer, "
+ "smarter and faster Internet experience."
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def query(self, qaddr):
+ res = dns.resolver.Resolver()
+ res.nameservers = ["8.26.56.26", "8.20.247.20"]
+
+ try:
+ addrs = res.resolve(qaddr)
+ self.debug(f"Addresses returned: {addrs}")
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+ return False
+
+ if addrs:
+ return True
+ return False
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ # Check that it resolves first, as it becomes a valid
+ # malicious host only if NOT resolved by Comodo Secure DNS.
+ if not self.sf.resolveHost(eventData) and not self.sf.resolveHost6(eventData):
+ return
+
+ found = self.query(eventData)
+
+ # Host was found, not blocked
+ if found:
+ return
+
+ evt = SpiderFootEvent(blacklist_type, f"Comodo Secure DNS [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(malicious_type, f"Comodo Secure DNS [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_comodo class
diff --git a/spiderfoot/modules/sfp_company.py b/spiderfoot/modules/sfp_company.py
new file mode 100644
index 0000000000000000000000000000000000000000..c315752d2ce7700715d85ab2613cd6fa7a8343e7
--- /dev/null
+++ b/spiderfoot/modules/sfp_company.py
@@ -0,0 +1,162 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_company
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying company names.
+#
+# Author: Steve Micallef
+#
+# Created: 09/09/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_company(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Company Name Extractor",
+ 'summary': "Identify company names in any obtained data.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {
+ 'filterjscss': True
+ }
+
+ optdescs = {
+ 'filterjscss': "Filter out company names that originated from CSS/JS content. Enabling this avoids detection of popular Javascript and web framework author company names."
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT", "SSL_CERTIFICATE_ISSUED",
+ "DOMAIN_WHOIS", "NETBLOCK_WHOIS",
+ "AFFILIATE_DOMAIN_WHOIS", "AFFILIATE_WEB_CONTENT"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["COMPANY_NAME", "AFFILIATE_COMPANY_NAME"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ # Various ways to identify companies in text
+ # Support up to three word company names with each starting with
+ # a capital letter, allowing for hyphens brackets and numbers within.
+ pattern_prefix = r"(?=[,;:\'\">\(= ]|^)\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.][^ \"\';:><]*)?\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.]?[^ \"\';:><]*|[Aa]nd)?\s?([A-Z0-9\(\)][A-Za-z0-9\-&,\.]?[^ \"\';:><]*)?\s+"
+ pattern_match_re = [
+ 'LLC', r'L\.L\.C\.?', 'AG', r'A\.G\.?', 'GmbH', r'Pty\.?\s+Ltd\.?',
+ r'Ltd\.?', r'Pte\.?', r'Inc\.?', r'INC\.?', 'Incorporated', 'Foundation',
+ r'Corp\.?', 'Corporation', 'SA', r'S\.A\.?', 'SIA', 'BV', r'B\.V\.?',
+ 'NV', r'N\.V\.?', 'PLC', 'Limited', r'Pvt\.?\s+Ltd\.?', 'SARL']
+ pattern_match = [
+ 'LLC', 'L.L.C', 'AG', 'A.G', 'GmbH', 'Pty',
+ 'Ltd', 'Pte', 'Inc', 'INC', 'Foundation',
+ 'Corp', 'SA', 'S.A', 'SIA', 'BV', 'B.V',
+ 'NV', 'N.V', 'PLC', 'Limited', 'Pvt.', 'SARL']
+
+ pattern_suffix = r"(?=[ \.,:<\)\'\"]|[$\n\r])"
+
+ # Filter out anything from the company name which matches the below
+ filterpatterns = [
+ "Copyright",
+ r"\d{4}" # To catch years
+ ]
+
+ # Don't re-parse company names
+ if eventName in ["COMPANY_NAME", "AFFILIATE_COMPANY_NAME"]:
+ return
+
+ if eventName == "TARGET_WEB_CONTENT":
+ url = event.actualSource
+ if self.opts['filterjscss'] and (".js" in url or ".css" in url):
+ self.debug("Ignoring web content from CSS/JS.")
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName} ({len(eventData)} bytes)")
+
+ # Strip out everything before the O=
+ try:
+ if eventName == "SSL_CERTIFICATE_ISSUED":
+ eventData = eventData.split("O=")[1]
+ except Exception:
+ self.debug("Couldn't strip out 'O=' from certificate issuer, proceeding anyway...")
+
+ # Find chunks of text containing what might be a company name first.
+ # This is to avoid running very expensive regexps on large chunks of
+ # data.
+ chunks = list()
+ for pat in pattern_match:
+ start = 0
+ m = eventData.find(pat, start)
+ while m > 0:
+ start = m - 50
+ if start < 0:
+ start = 0
+ end = m + 10
+ if end >= len(eventData):
+ end = len(eventData) - 1
+ chunks.append(eventData[start:end])
+ offset = m + len(pat)
+ m = eventData.find(pat, offset)
+
+ myres = list()
+ for chunk in chunks:
+ for pat in pattern_match_re:
+ matches = re.findall(pattern_prefix + "(" + pat + ")" + pattern_suffix, chunk, re.MULTILINE | re.DOTALL)
+ for match in matches:
+ matched = 0
+ for m in match:
+ if len(m) > 0:
+ matched += 1
+ if matched <= 1:
+ continue
+
+ fullcompany = ""
+ for m in match:
+ flt = False
+ for f in filterpatterns:
+ if re.match(f, m):
+ flt = True
+ if not flt:
+ fullcompany += m + " "
+
+ fullcompany = re.sub(r"\s+", " ", fullcompany.strip())
+
+ self.info("Found company name: " + fullcompany)
+
+ if fullcompany in myres:
+ self.debug("Already found from this source.")
+ continue
+
+ myres.append(fullcompany)
+
+ if "AFFILIATE_" in eventName:
+ etype = "AFFILIATE_COMPANY_NAME"
+ else:
+ etype = "COMPANY_NAME"
+
+ evt = SpiderFootEvent(etype, fullcompany, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+# End of sfp_company class
diff --git a/spiderfoot/modules/sfp_cookie.py b/spiderfoot/modules/sfp_cookie.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb0fd4c6af5ea003696313a10dff2deab7c8c00f
--- /dev/null
+++ b/spiderfoot/modules/sfp_cookie.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cookie
+# Purpose: SpiderFoot plug-in for extracting cookies from HTTP headers.
+#
+# Author: Steve Micallef
+#
+# Created: 06/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cookie(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Cookie Extractor",
+ 'summary': "Extract Cookies from HTTP headers.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {}
+ optdescs = {}
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["WEBSERVER_HTTPHEADERS"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["TARGET_WEB_COOKIE"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventSource = event.actualSource
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventSource in self.results:
+ return
+
+ self.results[eventSource] = True
+
+ fqdn = self.sf.urlFQDN(eventSource)
+ if not self.getTarget().matches(fqdn):
+ self.debug(f"Not collecting cookies from external sites. Ignoring HTTP headers from {fqdn}")
+ return
+
+ try:
+ data = json.loads(eventData)
+ except Exception:
+ self.error("Received HTTP headers from another module in an unexpected format.")
+ return
+
+ cookie = data.get('cookie')
+ if cookie:
+ evt = SpiderFootEvent("TARGET_WEB_COOKIE", cookie, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_cookie class
diff --git a/spiderfoot/modules/sfp_countryname.py b/spiderfoot/modules/sfp_countryname.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eee0253b7cdfab76b8e78bb699151f7a009e7b7
--- /dev/null
+++ b/spiderfoot/modules/sfp_countryname.py
@@ -0,0 +1,236 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_countryname
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_iban, sfp_phone, sfp_whois) and identifying country names
+#
+# Author: Krishnasis Mandal
+#
+# Created: 28/04/2020
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+import phonenumbers
+from phonenumbers.phonenumberutil import region_code_for_country_code
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_countryname(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Country Name Extractor",
+ 'summary': "Identify country names in any obtained data.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {
+ 'cohosted': True,
+ 'affiliate': True,
+ 'noncountrytld': True,
+ 'similardomain': False,
+ }
+
+ optdescs = {
+ 'cohosted': "Obtain country name from co-hosted sites",
+ 'affiliate': "Obtain country name from affiliate sites",
+ 'noncountrytld': "Parse TLDs not associated with any country as default country domains",
+ 'similardomain': "Obtain country name from similar domains"
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ def detectCountryFromPhone(self, srcPhoneNumber: str) -> str:
+ """Lookup name of country from phone number region code.
+
+ Args:
+ srcPhoneNumber (str): phone number
+
+ Returns:
+ str: country name
+ """
+
+ if not isinstance(srcPhoneNumber, str):
+ return None
+
+ try:
+ phoneNumber = phonenumbers.parse(srcPhoneNumber)
+ except Exception:
+ self.debug(f"Skipped invalid phone number: {srcPhoneNumber}")
+ return None
+
+ try:
+ countryCode = region_code_for_country_code(phoneNumber.country_code)
+ except Exception:
+ self.debug(f"Lookup of region code failed for phone number: {srcPhoneNumber}")
+ return None
+
+ if not countryCode:
+ return None
+
+ return SpiderFootHelpers.countryNameFromCountryCode(countryCode.upper())
+
+ def detectCountryFromDomainName(self, srcDomain: str) -> str:
+ """Lookup name of country from TLD of domain name.
+
+ Args:
+ srcDomain (str): domain
+
+ Returns:
+ str: country name
+ """
+ if not isinstance(srcDomain, str):
+ return None
+
+ # Split domain into parts by '.'
+ # Country TLDs are reserved
+ domainParts = srcDomain.split(".")
+
+ # Search for country TLD in the domain parts - reversed
+ for part in domainParts[::-1]:
+ country_name = SpiderFootHelpers.countryNameFromTld(part)
+ if country_name:
+ return country_name
+
+ return None
+
+ def detectCountryFromIBAN(self, srcIBAN: str) -> str:
+ """Detect name of country from IBAN.
+
+ Args:
+ srcIBAN (str): IBAN
+
+ Returns:
+ str: country name
+ """
+ if not isinstance(srcIBAN, str):
+ return None
+
+ return SpiderFootHelpers.countryNameFromCountryCode(srcIBAN[0:2])
+
+ def detectCountryFromData(self, srcData: str) -> list:
+ """Detect name of country from event data (WHOIS lookup, Geo Info, Physical Address, etc)
+
+ Args:
+ srcData (str): event data
+
+ Returns:
+ list: list of countries
+ """
+ countries = list()
+
+ if not srcData:
+ return countries
+
+ # Get dictionary of country codes and country names
+ abbvCountryCodes = SpiderFootHelpers.countryCodes()
+
+ # Look for countrycodes and country in source data
+ for countryName in abbvCountryCodes.values():
+ if countryName.lower() not in srcData.lower():
+ continue
+
+ # Look for country name in source data
+ # Spaces are not included since "New Jersey" and others
+ # will get interpreted as "Jersey", etc.
+ matchCountries = re.findall(r"[,'\"\:\=\[\(\[\n\t\r\.] ?" + countryName + r"[,'\"\:\=\[\(\[\n\t\r\.]", srcData, re.IGNORECASE)
+
+ if matchCountries:
+ countries.append(countryName)
+
+ # Look for "Country: ", usually found in Whois records
+ matchCountries = re.findall("country: (.+?)", srcData, re.IGNORECASE)
+ if matchCountries:
+ for m in matchCountries:
+ m = m.strip()
+ if m in abbvCountryCodes:
+ countries.append(abbvCountryCodes[m])
+ if m in abbvCountryCodes.values():
+ countries.append(m)
+
+ return list(set(countries))
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IBAN_NUMBER", "PHONE_NUMBER", "AFFILIATE_DOMAIN_NAME",
+ "CO_HOSTED_SITE_DOMAIN", "DOMAIN_NAME", "SIMILARDOMAIN",
+ "AFFILIATE_DOMAIN_WHOIS", "CO_HOSTED_SITE_DOMAIN_WHOIS",
+ "DOMAIN_WHOIS", "GEOINFO", "PHYSICAL_ADDRESS"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["COUNTRY_NAME"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if event.moduleDataSource:
+ moduleDataSource = event.moduleDataSource
+ else:
+ moduleDataSource = "Unknown"
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ eventDataHash = self.sf.hashstring(eventData)
+
+ if eventDataHash in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventDataHash] = True
+
+ countryNames = list()
+
+ # Process the event data based on incoming event type
+ if eventName == "PHONE_NUMBER":
+ countryNames.append(self.detectCountryFromPhone(eventData))
+ elif eventName == "DOMAIN_NAME":
+ countryNames.append(self.detectCountryFromDomainName(eventData))
+ elif eventName == "AFFILIATE_DOMAIN_NAME" and self.opts["affiliate"]:
+ countryNames.append(self.detectCountryFromDomainName(eventData))
+ elif eventName == "CO_HOSTED_SITE_DOMAIN" and self.opts["cohosted"]:
+ countryNames.append(self.detectCountryFromDomainName(eventData))
+ elif eventName == "SIMILARDOMAIN" and self.opts["similardomain"]:
+ countryNames.append(self.detectCountryFromDomainName(eventData))
+ elif eventName == "IBAN_NUMBER":
+ countryNames.append(self.detectCountryFromIBAN(eventData))
+ elif eventName in ["DOMAIN_WHOIS", "GEOINFO", "PHYSICAL_ADDRESS"]:
+ countryNames.extend(self.detectCountryFromData(eventData))
+ elif eventName == "AFFILIATE_DOMAIN_WHOIS" and self.opts["affiliate"]:
+ countryNames.extend(self.detectCountryFromData(eventData))
+ elif eventName == "CO_HOSTED_SITE_DOMAIN_WHOIS" and self.opts["cohosted"]:
+ countryNames.extend(self.detectCountryFromData(eventData))
+
+ if not countryNames:
+ self.debug(f"Found no country names associated with {eventName}: {eventData}")
+ return
+
+ for countryName in set(countryNames):
+ if not countryName:
+ continue
+
+ self.debug(f"Found country name: {countryName}")
+
+ evt = SpiderFootEvent("COUNTRY_NAME", countryName, self.__name__, event)
+ evt.moduleDataSource = moduleDataSource
+ self.notifyListeners(evt)
+
+# End of sfp_countryname class
diff --git a/spiderfoot/modules/sfp_creditcard.py b/spiderfoot/modules/sfp_creditcard.py
new file mode 100644
index 0000000000000000000000000000000000000000..af3859b9cecc6ad21a81f3fcd4d31c7a2f58e5c2
--- /dev/null
+++ b/spiderfoot/modules/sfp_creditcard.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_creditcard
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying credit card numbers.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 21/04/2020
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_creditcard(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Credit Card Number Extractor",
+ 'summary': "Identify Credit Card Numbers in any data",
+ 'flags': ["errorprone"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Override datasource for sfp_creditcard module
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DARKNET_MENTION_CONTENT", "LEAKSITE_CONTENT"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["CREDIT_CARD_NUMBER"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ creditCards = SpiderFootHelpers.extractCreditCardsFromText(eventData)
+
+ for creditCard in set(creditCards):
+ self.info(f"Found credit card number: {creditCard}")
+ evt = SpiderFootEvent("CREDIT_CARD_NUMBER", creditCard, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+# End of sfp_creditcard class
diff --git a/spiderfoot/modules/sfp_crobat_api.py b/spiderfoot/modules/sfp_crobat_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..41db442a91a9ab6d24a468868cd963f2ad3fb94b
--- /dev/null
+++ b/spiderfoot/modules/sfp_crobat_api.py
@@ -0,0 +1,175 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_crobat_api
+# Purpose: Search Crobat API for subdomains.
+# https://www.onsecurity.co.uk/blog/how-i-made-rapid7s-project-sonar-searchable
+# https://github.com/cgboal/sonarsearch
+#
+# Authors:
+#
+# Created: 2020-08-29
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_crobat_api(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Crobat API",
+ 'summary': "Search Crobat API for subdomains.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://sonar.omnisint.io/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'logo': "https://sonar.omnisint.io/img/crobat.png",
+ 'description': "The entire Rapid7 Sonar DNS dataset indexed,"
+ " available at your fingertips.",
+ }
+ }
+
+ opts = {
+ "verify": True,
+ "max_pages": 10,
+ "delay": 1
+ }
+
+ optdescs = {
+ "verify": "DNS resolve each identified subdomain.",
+ "max_pages": "Maximum number of pages of results to fetch.",
+ "delay": "Delay between requests, in seconds."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "INTERNET_NAME", "INTERNET_NAME_UNRESOLVED"]
+
+ def queryDomain(self, qry, page=0):
+ headers = {
+ "Accept": "application/json"
+ }
+ params = urllib.parse.urlencode({
+ 'page': page
+ })
+ domain = qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ res = self.sf.fetchUrl(
+ f"https://sonar.omnisint.io/subdomains/{domain}?{params}",
+ headers=headers,
+ timeout=30,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Crobat API.")
+ return None
+
+ # Future proofing - Crobat API does not implement rate limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by Crobat API")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from Crobat API")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ # returns "null" when page has no data
+ if res['content'] == "null":
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if not isinstance(data, list):
+ self.error("Failed to retrieve content from Crobat API")
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName != "DOMAIN_NAME":
+ return
+
+ page = 0
+ while page < self.opts['max_pages']:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ data = self.queryDomain(eventData, page)
+
+ if not data:
+ self.debug(f"No information found for domain {eventData} (page: {page})")
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ page += 1
+
+ for domain in set(data):
+ if domain in self.results:
+ continue
+
+ if not self.getTarget().matches(domain, includeChildren=True, includeParents=True):
+ continue
+
+ if self.opts['verify'] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", domain, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("INTERNET_NAME", domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_crobat_api class
diff --git a/spiderfoot/modules/sfp_crossref.py b/spiderfoot/modules/sfp_crossref.py
new file mode 100644
index 0000000000000000000000000000000000000000..4739146f4f540ba8146d8a2440d2be62d098c5e5
--- /dev/null
+++ b/spiderfoot/modules/sfp_crossref.py
@@ -0,0 +1,179 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_crossref
+# Purpose: SpiderFoot plug-in for scanning links identified from the
+# spidering process, and for external links, fetching them to
+# see if those sites link back to the original site, indicating a
+# potential relationship between the external sites.
+#
+# Author: Steve Micallef
+#
+# Created: 06/04/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_crossref(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Cross-Referencer",
+ 'summary': "Identify whether other domains are associated ('Affiliates') of the target by looking for links back to the target site(s).",
+ 'flags': [],
+ 'useCases': ["Footprint"],
+ 'categories': ["Crawling and Scanning"]
+ }
+
+ opts = {
+ 'checkbase': True
+ }
+
+ optdescs = {
+ "checkbase": "Check the base URL of the potential affiliate if no direct affiliation found?"
+ }
+
+ fetched = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.fetched = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'LINKED_URL_EXTERNAL',
+ 'SIMILARDOMAIN',
+ 'CO_HOSTED_SITE',
+ 'DARKNET_MENTION_URL'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'AFFILIATE_INTERNET_NAME',
+ 'AFFILIATE_WEB_CONTENT'
+ ]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # SIMILARDOMAIN and CO_HOSTED_SITE events are domains, not URLs.
+ # Assume HTTP.
+ if eventName in ['SIMILARDOMAIN', 'CO_HOSTED_SITE']:
+ url = 'http://' + eventData.lower()
+ elif 'URL' in eventName:
+ url = eventData
+ else:
+ return
+
+ fqdn = self.sf.urlFQDN(url)
+
+ # We are only interested in external sites for the crossref
+ if self.getTarget().matches(fqdn):
+ self.debug(f"Ignoring {url} as not external")
+ return
+
+ if eventData in self.fetched:
+ self.debug(f"Ignoring {url} as already tested")
+ return
+
+ if not self.sf.resolveHost(fqdn) and not self.sf.resolveHost6(fqdn):
+ self.debug(f"Ignoring {url} as {fqdn} does not resolve")
+ return
+
+ self.fetched[url] = True
+
+ self.debug(f"Testing URL for affiliation: {url}")
+
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ sizeLimit=10000000,
+ verify=False
+ )
+
+ if res['content'] is None:
+ self.debug(f"Ignoring {url} as no data returned")
+ return
+
+ matched = False
+ for name in self.getTarget().getNames():
+ # Search for mentions of our host/domain in the external site's data
+ pat = re.compile(
+ r"([\.\'\/\"\ ]" + re.escape(name) + r"[\.\'\/\"\ ])",
+ re.IGNORECASE
+ )
+ matches = re.findall(pat, str(res['content']))
+
+ if len(matches) > 0:
+ matched = True
+ break
+
+ if not matched:
+ # If the name wasn't found in the affiliate, and checkbase is set,
+ # fetch the base URL of the affiliate to check for a crossref.
+ if eventName == "LINKED_URL_EXTERNAL" and self.opts['checkbase']:
+ # Check the base url to see if there is an affiliation
+ url = SpiderFootHelpers.urlBaseUrl(eventData)
+ if url in self.fetched:
+ return
+
+ self.fetched[url] = True
+
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ sizeLimit=10000000,
+ verify=False
+ )
+
+ if res['content'] is not None:
+ for name in self.getTarget().getNames():
+ pat = re.compile(
+ r"([\.\'\/\"\ ]" + re.escape(name) + r"[\'\/\"\ ])",
+ re.IGNORECASE
+ )
+ matches = re.findall(pat, str(res['content']))
+
+ if len(matches) > 0:
+ matched = True
+ break
+
+ if not matched:
+ return
+
+ if not event.moduleDataSource:
+ event.moduleDataSource = "Unknown"
+
+ self.info(f"Found link to target from affiliate: {url}")
+
+ evt1 = SpiderFootEvent(
+ "AFFILIATE_INTERNET_NAME",
+ self.sf.urlFQDN(url),
+ self.__name__,
+ event
+ )
+ evt1.moduleDataSource = event.moduleDataSource
+ self.notifyListeners(evt1)
+
+ evt2 = SpiderFootEvent(
+ "AFFILIATE_WEB_CONTENT",
+ res['content'],
+ self.__name__,
+ evt1
+ )
+ evt2.moduleDataSource = event.moduleDataSource
+ self.notifyListeners(evt2)
+
+# End of sfp_crossref class
diff --git a/spiderfoot/modules/sfp_crt.py b/spiderfoot/modules/sfp_crt.py
new file mode 100644
index 0000000000000000000000000000000000000000..df508677c945becb2a1ec748f32f9dee39f941f8
--- /dev/null
+++ b/spiderfoot/modules/sfp_crt.py
@@ -0,0 +1,258 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_crt
+# Purpose: SpiderFoot plug-in to identify historical certificates for a domain
+# from crt.sh, and from this identify hostnames.
+#
+# Author: Steve Micallef
+#
+# Created: 17/03/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.parse
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_crt(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Certificate Transparency",
+ 'summary': "Gather hostnames from historical certificates in crt.sh.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://crt.sh/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://sectigo.com/",
+ "https://github.com/crtsh"
+ ],
+ 'favIcon': "https://crt.sh/sectigo_s.png",
+ 'logo': "https://crt.sh/sectigo_s.png",
+ 'description': "Free CT Log Certificate Search Tool from Sectigo (formerly Comodo CA)."
+ }
+ }
+
+ opts = {
+ 'verify': True,
+ 'fetchcerts': True,
+ }
+
+ optdescs = {
+ 'verify': 'Verify certificate subject alternative names resolve.',
+ 'fetchcerts': 'Fetch each certificate found, for processing by other modules.',
+ }
+
+ results = None
+ cert_ids = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+ self.cert_ids = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['DOMAIN_NAME', 'INTERNET_NAME']
+
+ def producedEvents(self):
+ return [
+ "SSL_CERTIFICATE_RAW",
+ "RAW_RIR_DATA",
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "DOMAIN_NAME",
+ "CO_HOSTED_SITE",
+ "CO_HOSTED_SITE_DOMAIN"
+ ]
+
+ def queryDomain(self, qry: str):
+ params = {
+ 'q': '%.' + qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'output': 'json'
+ }
+
+ res = self.sf.fetchUrl(
+ "https://crt.sh/?" + urllib.parse.urlencode(params),
+ timeout=30,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(0.5)
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from crt.sh")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results for query")
+ return None
+
+ # Future proofing - crt.sh does not implement rate limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by crt.sh")
+ self.errorState = True
+ return None
+
+ if res['code'] == '500' or res['code'] == '502' or res['code'] == '503':
+ self.error("crt.sh service is unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all other non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from crt.sh")
+ self.errorState = True
+ return None
+
+ if not res['content']:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ if event.data in self.results:
+ return
+
+ self.results[event.data] = True
+
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ data = self.queryDomain(event.data)
+
+ if not data:
+ self.debug(f"No certificate transparency results for domain {event.data}")
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ domains = list()
+ certs = list()
+
+ # Extract all domains and certificate IDs from each certificate
+ for cert_info in data:
+ cert_id = cert_info.get('id')
+
+ if not cert_id:
+ continue
+
+ if cert_id in self.cert_ids:
+ continue
+
+ self.cert_ids[cert_id] = True
+
+ if self.opts['fetchcerts']:
+ certs.append(cert_id)
+
+ domain = cert_info.get('name_value')
+
+ if not domain:
+ continue
+
+ for d in domain.split("\n"):
+ if d.lower() == event.data.lower():
+ continue
+ domains.append(d.lower().replace("*.", ""))
+
+ if self.opts['fetchcerts'] and len(certs) > 0:
+ self.info(f"Retrieving {len(set(certs))} certificates ...")
+
+ # Fetch and store each certificate
+ # Report SAN domains for each certificate
+ for cert_id in set(certs):
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ break
+
+ params = {
+ 'd': str(cert_id)
+ }
+
+ res = self.sf.fetchUrl(
+ 'https://crt.sh/?' + urllib.parse.urlencode(params),
+ timeout=30,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(0.5)
+
+ if not res or not res['content']:
+ self.error(f"Error retrieving certificate with ID {cert_id}. No response from crt.sh")
+ continue
+
+ try:
+ cert = self.sf.parseCert(str(res['content']))
+ except Exception as e:
+ self.info(f"Error parsing certificate: {e}")
+ continue
+
+ cert_text = cert.get('text')
+
+ if cert_text:
+ evt = SpiderFootEvent("SSL_CERTIFICATE_RAW", str(cert_text), self.__name__, event)
+ self.notifyListeners(evt)
+
+ sans = cert.get('altnames', list())
+
+ if not sans:
+ continue
+
+ for san in sans:
+ if san.lower() == event.data.lower():
+ continue
+ domains.append(san.lower().replace("*.", ""))
+
+ if self.opts['verify'] and len(domains) > 0:
+ self.info(f"Resolving {len(set(domains))} domains ...")
+
+ for domain in set(domains):
+ if domain in self.results:
+ continue
+
+ if not self.sf.validHost(domain, self.opts['_internettlds']):
+ continue
+
+ if self.getTarget().matches(domain, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ if self.opts['verify'] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt_type += '_UNRESOLVED'
+ else:
+ evt_type = 'CO_HOSTED_SITE'
+
+ evt = SpiderFootEvent(evt_type, domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(domain, self.opts['_internettlds']):
+ if evt_type == 'CO_HOSTED_SITE':
+ evt = SpiderFootEvent('CO_HOSTED_SITE_DOMAIN', domain, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent('DOMAIN_NAME', domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_crt class
diff --git a/spiderfoot/modules/sfp_crxcavator.py b/spiderfoot/modules/sfp_crxcavator.py
new file mode 100644
index 0000000000000000000000000000000000000000..3684ff8e5d49534406e1832cc04abe8bd5613fe1
--- /dev/null
+++ b/spiderfoot/modules/sfp_crxcavator.py
@@ -0,0 +1,283 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_crxcavator
+# Purpose: Query CRXcavator for Chrome extensions.
+#
+# Author:
+#
+# Created: 2020-09-19
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_crxcavator(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CRXcavator",
+ 'summary': "Search CRXcavator for Chrome extensions.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://crxcavator.io/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'favIcon': "https://crxcavator.io/favicon-32x32.png",
+ 'logo': "https://crxcavator.io/apple-touch-icon.png",
+ 'description': "CRXcavator automatically scans the entire Chrome Web "
+ "Store every 3 hours and produces a quantified risk score for "
+ "each Chrome Extension based on several factors.",
+ }
+ }
+
+ opts = {
+ "verify": True,
+ }
+
+ optdescs = {
+ "verify": "Verify identified hostnames resolve.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'DOMAIN_NAME'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'APPSTORE_ENTRY',
+ 'INTERNET_NAME',
+ 'INTERNET_NAME_UNRESOLVED',
+ 'LINKED_URL_INTERNAL',
+ 'AFFILIATE_INTERNET_NAME',
+ 'AFFILIATE_INTERNET_NAME_UNRESOLVED',
+ 'PHYSICAL_ADDRESS',
+ 'RAW_RIR_DATA'
+ ]
+
+ def query(self, qry):
+ params = urllib.parse.urlencode({
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.crxcavator.io/v1/search?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from CRXcavator: {e}")
+ return None
+
+ if not data:
+ self.debug(f"No results found for {qry}")
+ return None
+
+ return data
+
+ def queryExtension(self, extension_id):
+ res = self.sf.fetchUrl(
+ f"https://api.crxcavator.io/v1/report/{extension_id}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from CRXcavator: {e}")
+ return None
+
+ if not data:
+ self.debug(f"No results found for extension {extension_id}")
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if eventName not in self.watchedEvents():
+ return
+
+ self.results[eventData] = True
+
+ domain_keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ results = self.query(domain_keyword)
+
+ if not results:
+ self.info(f"No results found for {domain_keyword}")
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', json.dumps(results), self.__name__, event)
+ self.notifyListeners(evt)
+
+ urls = list()
+ hosts = list()
+ locations = list()
+
+ for result in results:
+ if not isinstance(result, dict):
+ continue
+
+ extension_id = result.get('extension_id')
+
+ if not extension_id:
+ continue
+
+ if '@' in extension_id:
+ continue
+
+ extensions = self.queryExtension(extension_id)
+
+ if not extensions:
+ continue
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', json.dumps(extensions), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for extension in extensions:
+ data = extension.get('data')
+
+ if not data:
+ continue
+
+ manifest = data.get('manifest')
+
+ if not manifest:
+ continue
+
+ version = manifest.get('version')
+
+ if not version:
+ continue
+
+ webstore = data.get('webstore')
+
+ if not webstore:
+ continue
+
+ name = webstore.get('name')
+
+ if not name:
+ continue
+
+ app_full_name = f"{name} {version} ({extension_id})"
+
+ privacy_policy = webstore.get('privacy_policy')
+ support_site = webstore.get('support_site')
+ offered_by = webstore.get('offered_by')
+ website = webstore.get('website')
+
+ if not privacy_policy and not support_site and not offered_by and not website:
+ continue
+
+ if (
+ not self.getTarget().matches(self.sf.urlFQDN(privacy_policy), includeChildren=True, includeParents=True)
+ and not self.getTarget().matches(self.sf.urlFQDN(website), includeChildren=True, includeParents=True)
+ and not self.getTarget().matches(self.sf.urlFQDN(offered_by), includeChildren=True, includeParents=True)
+ and not self.getTarget().matches(self.sf.urlFQDN(support_site), includeChildren=True, includeParents=True)
+ ):
+ self.debug(f"Extension {app_full_name} does not match {eventData}, skipping")
+ continue
+
+ app_data = f"{name} {version}\nhttps://chrome.google.com/webstore/detail/{extension_id} "
+
+ evt = SpiderFootEvent('APPSTORE_ENTRY', app_data, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if privacy_policy:
+ urls.append(privacy_policy)
+
+ if support_site:
+ urls.append(support_site)
+
+ if website:
+ urls.append(website)
+
+ if offered_by:
+ urls.append(offered_by)
+
+ address = webstore.get('address')
+
+ if address and len(address) > 10:
+ locations.append(address)
+
+ for url in set(urls):
+ if not url:
+ continue
+
+ host = self.sf.urlFQDN(url)
+
+ if not host:
+ continue
+
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', url, self.__name__, event)
+ self.notifyListeners(evt)
+
+ hosts.append(host)
+
+ for host in set(hosts):
+ if not host:
+ continue
+
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ else:
+ evt_type = 'AFFILIATE_INTERNET_NAME'
+
+ if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt_type += '_UNRESOLVED'
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for location in set(locations):
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_crxcavator class
diff --git a/spiderfoot/modules/sfp_customfeed.py b/spiderfoot/modules/sfp_customfeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbd5ae9615974f2aa537a209625e42982e652dfa
--- /dev/null
+++ b/spiderfoot/modules/sfp_customfeed.py
@@ -0,0 +1,247 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_customfeed
+# Purpose: Checks if an ASN, IP, hostname or domain is listed as malicious
+# in a user-supplied data feed.
+#
+# Author: steve@binarypool.com
+#
+# Created: 11/11/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+malchecks = {
+ 'Custom Threat Data': {
+ 'id': '_customfeed',
+ 'checks': ['ip', 'netblock', 'asn', 'domain'],
+ 'regex': '^{0}$'
+ }
+}
+
+
+class sfp_customfeed(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Custom Threat Feed",
+ 'summary': "Check if a host/domain, netblock, ASN or IP is malicious according to your custom feed.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"]
+ }
+
+ # Default options
+ opts = {
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'url': "",
+ 'cacheperiod': 0
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'url': "The URL where the feed can be found. Exact matching is performed so the format must be a single line per host, ASN, domain, IP or netblock.",
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Maximum age of data in hours before re-downloading. 0 to always download."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ # * = be notified about all events.
+ def watchedEvents(self):
+ return ["INTERNET_NAME", "IP_ADDRESS", "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_IPADDR", "CO_HOSTED_SITE"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST"]
+
+ # Look up 'list' type resources
+ def resourceList(self, replaceme_id, target, targetType):
+ targetDom = ''
+ # Get the base domain if we're supplied a domain
+ if targetType == "domain":
+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])
+ if not targetDom:
+ return None
+
+ for check in list(malchecks.keys()):
+ cid = malchecks[check]['id']
+ url = self.opts['url']
+ if replaceme_id == cid:
+ data = dict()
+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))
+ if data['content'] is None:
+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+ if data['content'] is None:
+ self.error("Unable to fetch " + url)
+ return None
+ self.sf.cachePut("sfmal_" + cid, data['content'])
+
+ # If we're looking at netblocks
+ if targetType == "netblock":
+ iplist = list()
+ # Get the regex, replace {0} with an IP address matcher to
+ # build a list of IP.
+ # Cycle through each IP and check if it's in the netblock.
+ if 'regex' in malchecks[check]:
+ rx = malchecks[check]['regex'].replace("{0}", r"(\d+\.\d+\.\d+\.\d+)")
+ pat = re.compile(rx, re.IGNORECASE)
+ self.debug("New regex for " + check + ": " + rx)
+ for line in data['content'].split('\n'):
+ grp = re.findall(pat, line)
+ if len(grp) > 0:
+ # self.debug("Adding " + grp[0] + " to list.")
+ iplist.append(grp[0])
+ else:
+ iplist = data['content'].split('\n')
+
+ for ip in iplist:
+ if len(ip) < 8 or ip.startswith("#"):
+ continue
+ ip = ip.strip()
+
+ try:
+ if IPAddress(ip) in IPNetwork(target):
+ self.debug(f"{ip} found within netblock/subnet {target} in {check}")
+ return url
+ except Exception as e:
+ self.debug(f"Error encountered parsing: {e}")
+ continue
+
+ return None
+
+ # If we're looking at hostnames/domains/IPs
+ if 'regex' not in malchecks[check]:
+ for line in data['content'].split('\n'):
+ if line == target or (targetType == "domain" and line == targetDom):
+ self.debug(target + "/" + targetDom + " found in " + check + " list.")
+ return url
+ else:
+ # Check for the domain and the hostname
+ try:
+ rxDom = str(malchecks[check]['regex']).format(targetDom)
+ rxTgt = str(malchecks[check]['regex']).format(target)
+ for line in data['content'].split('\n'):
+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \
+ re.match(rxTgt, line, re.IGNORECASE):
+ self.debug(target + "/" + targetDom + " found in " + check + " list.")
+ return url
+ except Exception as e:
+ self.debug("Error encountered parsing 2: " + str(e))
+ continue
+
+ return None
+
+ def lookupItem(self, resourceId, itemType, target):
+ for check in list(malchecks.keys()):
+ cid = malchecks[check]['id']
+ if cid == resourceId and itemType in malchecks[check]['checks']:
+ self.debug("Checking maliciousness of " + target + " ("
+ + itemType + ") with: " + cid)
+ return self.resourceList(cid, target, itemType)
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if self.opts['url'] == "":
+ self.error("You enabled sfp_customfeed but defined no custom feed URL!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):
+ return
+ if eventName == 'AFFILIATE_IPADDR' \
+ and not self.opts.get('checkaffiliates', False):
+ return
+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):
+ return
+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):
+ return
+
+ for check in list(malchecks.keys()):
+ cid = malchecks[check]['id']
+
+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:
+ typeId = 'ip'
+ if eventName == 'IP_ADDRESS':
+ evtType = 'MALICIOUS_IPADDR'
+ else:
+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+
+ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:
+ typeId = 'asn'
+ evtType = 'MALICIOUS_ASN'
+
+ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',
+ 'AFFILIATE_INTERNET_NAME', ]:
+ typeId = 'domain'
+ if eventName == "INTERNET_NAME":
+ evtType = "MALICIOUS_INTERNET_NAME"
+ if eventName == 'AFFILIATE_INTERNET_NAME':
+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'
+ if eventName == 'CO_HOSTED_SITE':
+ evtType = 'MALICIOUS_COHOST'
+
+ if eventName == 'NETBLOCK_OWNER':
+ typeId = 'netblock'
+ evtType = 'MALICIOUS_NETBLOCK'
+ if eventName == 'NETBLOCK_MEMBER':
+ typeId = 'netblock'
+ evtType = 'MALICIOUS_SUBNET'
+
+ url = self.lookupItem(cid, typeId, eventData)
+
+ if self.checkForStop():
+ return
+
+ # Notify other modules of what you've found
+ if url is not None:
+ text = f"{check} [{eventData}]\n{url} "
+ evt = SpiderFootEvent(evtType, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_customfeed class
diff --git a/spiderfoot/modules/sfp_cybercrimetracker.py b/spiderfoot/modules/sfp_cybercrimetracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..4389f4df7e890b5f43005f0b5fed8c842a641374
--- /dev/null
+++ b/spiderfoot/modules/sfp_cybercrimetracker.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_cybercrimetracker
+# Purpose: Check if a host/domain or IP address is malicious according to cybercrime-tracker.net.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_cybercrimetracker(SpiderFootPlugin):
+
+ meta = {
+ 'name': "CyberCrime-Tracker.net",
+ 'summary': "Check if a host/domain or IP address is malicious according to CyberCrime-Tracker.net.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://cybercrime-tracker.net/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://cybercrime-tracker.net/tools.php",
+ "https://cybercrime-tracker.net/about.php"
+ ],
+ 'favIcon': "https://cybercrime-tracker.net/favicon.ico",
+ 'logo': "https://cybercrime-tracker.net/favicon.ico",
+ 'description': "CyberCrime is a C&C panel tracker, in other words, "
+ "it lists the administration interfaces of certain in-the-wild botnets.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'cacheperiod': 18
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Hours to cache list data before re-fetching."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "IP_ADDRESS",
+ "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_IPADDR",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST"
+ ]
+
+ def queryBlacklist(self, target):
+ blacklist = self.retrieveBlacklist()
+
+ if not blacklist:
+ return False
+
+ if target.lower() in blacklist:
+ self.debug(f"Host name {target} found in CyberCrime-Tracker.net blacklist.")
+ return True
+
+ return False
+
+ def retrieveBlacklist(self):
+ blacklist = self.sf.cacheGet('cybercrime-tracker', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://cybercrime-tracker.net/all.php",
+ timeout=10,
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from CyberCrime-Tracker.net.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from CyberCrime-Tracker.net")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("cybercrime-tracker", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from CyberCrime-Tracker.net
+
+ Returns:
+ list: list of blacklisted IP addresses and host names
+ """
+ hosts = list()
+
+ if not blacklist:
+ return hosts
+
+ for line in blacklist.split('\n'):
+ if not line:
+ continue
+ if line.startswith('#'):
+ continue
+
+ # Note: URL parsing and validation with sf.validHost() is too slow to use here
+ host = line.split("/")[0]
+ if not host:
+ continue
+ if "." not in host:
+ continue
+ hosts.append(host.split(':')[0])
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with CyberCrime-Tracker.net")
+
+ if not self.queryBlacklist(eventData):
+ return
+
+ url = f"https://cybercrime-tracker.net/index.php?search={eventData}"
+ text = f"CyberCrime-Tracker.net Malicious Submissions [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_cybercrimetracker class
diff --git a/spiderfoot/modules/sfp_debounce.py b/spiderfoot/modules/sfp_debounce.py
new file mode 100644
index 0000000000000000000000000000000000000000..70598c3a307228d3c90bf1ea71197b34949e1dd6
--- /dev/null
+++ b/spiderfoot/modules/sfp_debounce.py
@@ -0,0 +1,114 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_debounce
+# Purpose: Spiderfoot plugin to check if an email is
+# disposable using Debounce API.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 2020-10-01
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_debounce(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Debounce",
+ 'summary': "Check whether an email is disposable",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://debounce.io/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://debounce.io/free-disposable-check-api/"
+ ],
+ 'favIcon': "https://debounce.io/wp-content/uploads/2018/01/favicon-2.png",
+ 'logo': "https://debounce.io/wp-content/uploads/2018/01/debounce-logo-2.png",
+ 'description': "DeBounce provides a free & powerful API endpoint for checking "
+ "a domain or email address against a realtime up-to-date list of disposable domains."
+ "CORS is enabled for all originating domains, "
+ "so you can call the API directly from your client-side code.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "EMAILADDR"
+ ]
+
+ def producedEvents(self):
+ return [
+ "EMAILADDR_DISPOSABLE",
+ "RAW_RIR_DATA"
+ ]
+
+ def queryEmailAddr(self, qry):
+ res = self.sf.fetchUrl(
+ f"https://disposable.debounce.io?email={qry}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot"
+ )
+
+ if res['content'] is None:
+ self.info(f"No Debounce info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from Debounce: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ self.results[eventData] = True
+
+ data = self.queryEmailAddr(eventData)
+
+ if data is None:
+ return
+
+ isDisposable = data.get('disposable')
+
+ if isDisposable == "true":
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent("EMAILADDR_DISPOSABLE", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_debounce class
diff --git a/spiderfoot/modules/sfp_dehashed.py b/spiderfoot/modules/sfp_dehashed.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e7dab59da527c2f2b0020a210a2f9de14e19f4
--- /dev/null
+++ b/spiderfoot/modules/sfp_dehashed.py
@@ -0,0 +1,239 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_dehashed
+# Purpose: Gather breach data from Dehashed API.
+#
+# Author:
+#
+# Created: 16-01-2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dehashed(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Dehashed",
+ 'summary': "Gather breach data from Dehashed API.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "https://www.dehashed.com/",
+ 'model': "COMMERCIAL_ONLY",
+ 'references': [
+ "https://www.dehashed.com/docs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.dehashed.com/register"
+ "Register a free account",
+ "Visit https://www.dehashed.com/profile",
+ "Your API key is listed under 'API Key'",
+ ],
+ 'favIcon': "https://www.dehashed.com/assets/img/favicon.ico",
+ 'logo': "https://www.dehashed.com/assets/img/logo.png",
+ 'description': "Have you been compromised? "
+ "DeHashed provides free deep-web scans and protection against credential leaks. "
+ "A modern personal asset search engine created for "
+ "security analysts, journalists, security companies, "
+ "and everyday people to help secure accounts and provide insight on compromised assets. "
+ "Free breach alerts & breach notifications.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key_username': '',
+ 'api_key': '',
+ 'per_page': 10000,
+ 'max_pages': 2,
+ 'pause': 1
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key_username': 'Dehashed username.',
+ 'api_key': 'Dehashed API key.',
+ 'per_page': 'Maximum number of results per page.(Max: 10000)',
+ 'max_pages': 'Maximum number of pages to fetch(Max: 10 pages)',
+ 'pause': 'Number of seconds to wait between each API call.'
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ "EMAILADDR"
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ 'EMAILADDR',
+ 'EMAILADDR_COMPROMISED',
+ 'PASSWORD_COMPROMISED',
+ 'HASH_COMPROMISED',
+ 'RAW_RIR_DATA'
+ ]
+
+ # Query Dehashed
+ def query(self, event, per_page, start):
+ if event.eventType == "EMAILADDR":
+ queryString = f"https://api.dehashed.com/search?query=email:\"{event.data}\"&page={start}&size={self.opts['per_page']}"
+ if event.eventType == "DOMAIN_NAME":
+ queryString = f"https://api.dehashed.com/search?query=email:\"@{event.data}\"&page={start}&size={self.opts['per_page']}"
+
+ token = (base64.b64encode(self.opts['api_key_username'].encode('utf8') + ":".encode('utf-8') + self.opts['api_key'].encode('utf-8'))).decode('utf-8')
+ headers = {
+ 'Accept': 'application/json',
+ 'Authorization': f'Basic {token}'
+ }
+
+ res = self.sf.fetchUrl(queryString,
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent'],
+ verify=True)
+
+ time.sleep(self.opts['pause'])
+
+ if res['code'] == "400":
+ self.error("Too many requests were performed in a small amount of time. Please wait a bit before querying the API.")
+ time.sleep(5)
+ res = self.sf.fetchUrl(queryString, headers=headers, timeout=15, useragent=self.opts['_useragent'], verify=True)
+
+ if res['code'] == "401":
+ self.error("Invalid API credentials")
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.error("Unable to fetch data from Dehashed.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.debug('No response from Dehashed')
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if srcModuleName == self.__name__:
+ return
+
+ if eventData in self.results:
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "" or self.opts['api_key_username'] == "":
+ self.error("You enabled sfp_dehashed but did not set an API key/API Key Username!")
+ self.errorState = True
+ return
+
+ currentPage = 1
+ maxPages = self.opts['max_pages']
+ perPage = self.opts['per_page']
+
+ while currentPage <= maxPages:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ break
+
+ data = self.query(event, perPage, currentPage)
+
+ if not data:
+ return
+
+ breachResults = set()
+ emailResults = set()
+
+ if not data.get('entries'):
+ return
+
+ for row in data.get('entries'):
+ email = row.get('email')
+ password = row.get('password')
+ passwordHash = row.get('hashed_password')
+ leakSource = row.get('database_name', 'Unknown')
+
+ if f"{email} [{leakSource}]" in breachResults:
+ continue
+
+ breachResults.add(f"{email} [{leakSource}]")
+
+ if eventName == "EMAILADDR":
+ if email == eventData:
+ evt = SpiderFootEvent('EMAILADDR_COMPROMISED', f"{email} [{leakSource}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if password:
+ evt = SpiderFootEvent('PASSWORD_COMPROMISED', f"{email}:{password} [{leakSource}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if passwordHash:
+ evt = SpiderFootEvent('HASH_COMPROMISED', f"{email}:{passwordHash} [{leakSource}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(row), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == "DOMAIN_NAME":
+ pevent = SpiderFootEvent("EMAILADDR", email, self.__name__, event)
+ if email not in emailResults:
+ self.notifyListeners(pevent)
+ emailResults.add(email)
+
+ evt = SpiderFootEvent('EMAILADDR_COMPROMISED', f"{email} [{leakSource}]", self.__name__, pevent)
+ self.notifyListeners(evt)
+
+ if password:
+ evt = SpiderFootEvent('PASSWORD_COMPROMISED', f"{email}:{password} [{leakSource}]", self.__name__, pevent)
+ self.notifyListeners(evt)
+
+ if passwordHash:
+ evt = SpiderFootEvent('HASH_COMPROMISED', f"{email}:{passwordHash} [{leakSource}]", self.__name__, pevent)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(row), self.__name__, pevent)
+ self.notifyListeners(evt)
+
+ currentPage += 1
+
+ if data.get('total') < self.opts['per_page']:
+ break
+
+# End of sfp_dehashed class
diff --git a/spiderfoot/modules/sfp_digitaloceanspace.py b/spiderfoot/modules/sfp_digitaloceanspace.py
new file mode 100644
index 0000000000000000000000000000000000000000..78b4c5bfbc9e1b48c9a8e3edd8cf93efb1613229
--- /dev/null
+++ b/spiderfoot/modules/sfp_digitaloceanspace.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_digitaloceanspace
+# Purpose: SpiderFoot plug-in for identifying potential Digital Ocean spaces
+# related to the target.
+#
+# Author: Steve Micallef
+#
+# Created: 16/06/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import random
+import threading
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_digitaloceanspace(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Digital Ocean Space Finder",
+ 'summary': "Search for potential Digital Ocean Spaces associated with the target and attempt to list their contents.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Crawling and Scanning"],
+ 'dataSource': {
+ 'website': "https://www.digitalocean.com/products/spaces/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'favIcon': 'https://www.digitalocean.com/_next/static/media/favicon-32x32.b7ef9ede.png',
+ 'logo': 'https://www.digitalocean.com/_next/static/media/logo.87a8f3b8.svg',
+ 'description': "Store and deliver vast amounts of content."
+ "S3-compatible object storage with a built-in CDN that makes scaling easy, reliable, and affordable."
+ }
+ }
+
+ # Default options
+ opts = {
+ "endpoints": "nyc3.digitaloceanspaces.com,sgp1.digitaloceanspaces.com,ams3.digitaloceanspaces.com",
+ "suffixes": "test,dev,web,beta,bucket,space,files,content,data,prod,staging,production,stage,app,media,development,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data,-prod,-staging,-production,-stage,-app,-media,-development",
+ "_maxthreads": 20
+ }
+
+ # Option descriptions
+ optdescs = {
+ "endpoints": "Different Digital Ocean locations to check where spaces may exist.",
+ "suffixes": "List of suffixes to append to domains tried as space names",
+ "_maxthreads": "Maximum threads"
+ }
+
+ results = None
+ s3results = dict()
+ lock = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.s3results = dict()
+ self.results = self.tempStorage()
+ self.lock = threading.Lock()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["CLOUD_STORAGE_BUCKET", "CLOUD_STORAGE_BUCKET_OPEN"]
+
+ def checkSite(self, url):
+ res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot", noLog=True)
+
+ if not res['content']:
+ return
+
+ if "NoSuchBucket" in res['content']:
+ self.debug(f"Not a valid bucket: {url}")
+ return
+
+ # Bucket found
+ if res['code'] in ["301", "302", "200"]:
+ # Bucket has files
+ if "ListBucketResult" in res['content']:
+ with self.lock:
+ self.s3results[url] = res['content'].count("")
+ else:
+ # Bucket has no files
+ with self.lock:
+ self.s3results[url] = 0
+
+ def threadSites(self, siteList):
+ self.s3results = dict()
+ running = True
+ i = 0
+ t = []
+
+ for site in siteList:
+ if self.checkForStop():
+ return None
+
+ self.info("Spawning thread to check bucket: " + site)
+ tname = str(random.SystemRandom().randint(0, 999999999))
+ t.append(threading.Thread(name='thread_sfp_digitaloceanspaces_' + tname,
+ target=self.checkSite, args=(site,)))
+ t[i].start()
+ i += 1
+
+ # Block until all threads are finished
+ while running:
+ found = False
+ for rt in threading.enumerate():
+ if rt.name.startswith("thread_sfp_digitaloceanspaces_"):
+ found = True
+
+ if not found:
+ running = False
+
+ time.sleep(0.25)
+
+ # Return once the scanning has completed
+ return self.s3results
+
+ def batchSites(self, sites):
+ i = 0
+ res = list()
+ siteList = list()
+
+ for site in sites:
+ if i >= self.opts['_maxthreads']:
+ data = self.threadSites(siteList)
+ if data is None:
+ return res
+
+ for ret in list(data.keys()):
+ if data[ret]:
+ # bucket:filecount
+ res.append(ret + ":" + str(data[ret]))
+ i = 0
+ siteList = list()
+
+ siteList.append(site)
+ i += 1
+
+ return res
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName == "LINKED_URL_EXTERNAL":
+ if ".digitaloceanspaces.com" in eventData:
+ b = self.sf.urlFQDN(eventData)
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", b, self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ targets = [eventData.replace('.', '')]
+ kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ if kw:
+ targets.append(kw)
+
+ urls = list()
+ for t in targets:
+ for e in self.opts['endpoints'].split(','):
+ suffixes = [''] + self.opts['suffixes'].split(',')
+ for s in suffixes:
+ if self.checkForStop():
+ return
+
+ b = t + s + "." + e
+ url = "https://" + b
+ urls.append(url)
+
+ # Batch the scans
+ ret = self.batchSites(urls)
+ for b in ret:
+ bucket = b.split(":")
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", bucket[0] + ":" + bucket[1], self.__name__, event)
+ self.notifyListeners(evt)
+ if bucket[2] != "0":
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET_OPEN", bucket[0] + ":" + bucket[1] + ": " + bucket[2] + " files found.",
+ self.__name__, evt)
+ self.notifyListeners(evt)
+
+
+# End of sfp_digitaloceanspace class
diff --git a/spiderfoot/modules/sfp_dns_for_family.py b/spiderfoot/modules/sfp_dns_for_family.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce73c461a44666e656ee6075ff8d25e9cdcaf12b
--- /dev/null
+++ b/spiderfoot/modules/sfp_dns_for_family.py
@@ -0,0 +1,118 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dns_for_family
+# Purpose: Check if a host would be blocked by DNS for Family.
+#
+# Author:
+#
+# Created: 2021-10-11
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dns_for_family(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS for Family",
+ 'summary': "Check if a host would be blocked by DNS for Family.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://dnsforfamily.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://dnsforfamily.com/",
+ ],
+ 'favIcon': "https://dnsforfamily.com/Icons/favicon-32x32.png",
+ 'logo': "https://dnsforfamily.com/Templates/assets/images/logo.svg",
+ 'description': "DNS for Family aims to block websites which are considered as porn. "
+ "So that you and your children can safely surf internet to their heart's desire, "
+ "without worrying to be followed to harmful websites."
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ ]
+
+ def queryAddr(self, qaddr):
+ if not qaddr:
+ return None
+
+ res = dns.resolver.Resolver()
+ res.nameservers = ["94.130.180.225", "78.47.64.161"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ res = self.queryAddr(eventData)
+
+ if not res:
+ return
+
+ for result in res:
+ k = str(result)
+ if k != '159.69.10.249':
+ continue
+
+ self.debug(f"{eventData} blocked by DNS for Family")
+ evt = SpiderFootEvent(blacklist_type, f"DNS for Family [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_dns_for_family class
diff --git a/spiderfoot/modules/sfp_dnsbrute.py b/spiderfoot/modules/sfp_dnsbrute.py
new file mode 100644
index 0000000000000000000000000000000000000000..1926add8bb5a0517e54f1691993335dcf25fb9c9
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsbrute.py
@@ -0,0 +1,237 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsbrute
+# Purpose: SpiderFoot plug-in for attempting to resolve through brute-forcing
+# common hostnames.
+#
+# Author: Steve Micallef
+#
+# Created: 06/07/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import importlib
+import random
+import threading
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsbrute(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Brute-forcer",
+ 'summary': "Attempts to identify hostnames through brute-forcing common names and iterations.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["DNS"]
+ }
+
+ # Default options
+ opts = {
+ "skipcommonwildcard": True,
+ "domainonly": True,
+ "commons": True,
+ "top10000": False,
+ "numbersuffix": True,
+ "numbersuffixlimit": True,
+ "_maxthreads": 100
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'skipcommonwildcard': "If wildcard DNS is detected, don't bother brute-forcing.",
+ 'domainonly': "Only attempt to brute-force names on domain names, not hostnames (some hostnames are also sub-domains).",
+ 'commons': "Try a list of about 750 common hostnames/sub-domains.",
+ 'top10000': "Try a further 10,000 common hostnames/sub-domains. Will make the scan much slower.",
+ 'numbersuffix': "For any host found, try appending 1, 01, 001, -1, -01, -001, 2, 02, etc. (up to 10)",
+ 'numbersuffixlimit': "Limit using the number suffixes for hosts that have already been resolved? If disabled this will significantly extend the duration of scans.",
+ "_maxthreads": "Maximum threads"
+ }
+
+ events = None
+ sublist = None
+ lock = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.sublist = self.tempStorage()
+ self.events = self.tempStorage()
+ self.__dataSource__ = "DNS"
+ self.lock = threading.Lock()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ if self.opts['commons']:
+ with importlib.resources.open_text('spiderfoot.dicts', 'subdomains.txt') as f:
+ for s in f.readlines():
+ s = s.strip()
+ self.sublist[s] = True
+
+ if self.opts['top10000']:
+ with importlib.resources.open_text('spiderfoot.dicts', 'subdomains-10000.txt') as f:
+ for s in f.readlines():
+ s = s.strip()
+ self.sublist[s] = True
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ ret = ['DOMAIN_NAME']
+ if not self.opts['domainonly'] or self.opts['numbersuffix']:
+ ret.append('INTERNET_NAME')
+ return ret
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["INTERNET_NAME"]
+
+ def tryHost(self, name):
+ try:
+ if self.sf.resolveHost(name) or self.sf.resolveHost6(name):
+ with self.lock:
+ self.hostResults[name] = True
+ except Exception:
+ with self.lock:
+ self.hostResults[name] = False
+
+ def tryHostWrapper(self, hostList, sourceEvent):
+ self.hostResults = dict()
+ running = True
+ i = 0
+ t = []
+
+ # Spawn threads for scanning
+ self.info("Spawning threads to check hosts: " + str(hostList))
+ for name in hostList:
+ tn = 'thread_sfp_dnsbrute_' + str(random.SystemRandom().randint(1, 999999999))
+ t.append(threading.Thread(name=tn, target=self.tryHost, args=(name,)))
+ t[i].start()
+ i += 1
+
+ # Block until all threads are finished
+ while running:
+ found = False
+ for rt in threading.enumerate():
+ if rt.name.startswith("thread_sfp_dnsbrute_"):
+ found = True
+
+ if not found:
+ running = False
+
+ time.sleep(0.05)
+
+ for res in self.hostResults:
+ if self.hostResults.get(res, False):
+ self.sendEvent(sourceEvent, res)
+
+ # Store the result internally and notify listening modules
+ def sendEvent(self, source, result):
+ self.info("Found a brute-forced host: " + result)
+ # Report the host
+ evt = SpiderFootEvent("INTERNET_NAME", result, self.__name__, source)
+ self.notifyListeners(evt)
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventDataHash = self.sf.hashstring(eventData)
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == "sfp_dnsbrute":
+ return
+
+ if eventDataHash in self.events:
+ return
+ self.events[eventDataHash] = True
+
+ if eventName == "INTERNET_NAME" and not self.getTarget().matches(eventData, includeChildren=False):
+ if not self.opts['numbersuffix']:
+ return
+
+ if self.checkForStop():
+ return
+
+ h, dom = eventData.split(".", 1)
+
+ # Try resolving common names
+ wildcard = self.sf.checkDnsWildcard(dom)
+ if self.opts['skipcommonwildcard'] and wildcard:
+ self.debug("Wildcard DNS detected on " + dom + " so skipping host iteration.")
+ return
+
+ dom = "." + dom
+ nextsubs = dict()
+ for i in range(10):
+ nextsubs[h + str(i) + dom] = True
+ nextsubs[h + "0" + str(i) + dom] = True
+ nextsubs[h + "00" + str(i) + dom] = True
+ nextsubs[h + "-" + str(i) + dom] = True
+ nextsubs[h + "-0" + str(i) + dom] = True
+ nextsubs[h + "-00" + str(i) + dom] = True
+
+ self.tryHostWrapper(list(nextsubs.keys()), event)
+
+ # The rest of the module is for handling targets only
+ return
+
+ # Only for the target, from this point forward...
+ if not self.getTarget().matches(eventData, includeChildren=False):
+ return
+
+ # Try resolving common names
+ self.debug("Iterating through possible sub-domains.")
+ wildcard = self.sf.checkDnsWildcard(eventData)
+ if self.opts['skipcommonwildcard'] and wildcard:
+ self.debug("Wildcard DNS detected.")
+ return
+
+ targetList = list()
+ for sub in self.sublist:
+ if self.checkForStop():
+ return
+
+ name = f"{sub}.{eventData}"
+
+ if len(targetList) <= self.opts['_maxthreads']:
+ targetList.append(name)
+ else:
+ self.tryHostWrapper(targetList, event)
+ targetList = list()
+
+ # Scan whatever may be left over.
+ if len(targetList) > 0:
+ self.tryHostWrapper(targetList, event)
+
+ if self.opts['numbersuffix'] and not self.opts['numbersuffixlimit']:
+ nextsubs = dict()
+ dom = "." + eventData
+ for s in self.sublist:
+ if self.checkForStop():
+ return
+
+ for i in range(10):
+ nextsubs[s + str(i) + dom] = True
+ nextsubs[s + "0" + str(i) + dom] = True
+ nextsubs[s + "00" + str(i) + dom] = True
+ nextsubs[s + "-" + str(i) + dom] = True
+ nextsubs[s + "-0" + str(i) + dom] = True
+ nextsubs[s + "-00" + str(i) + dom] = True
+
+ if len(list(nextsubs.keys())) >= self.opts['_maxthreads']:
+ self.tryHostWrapper(list(nextsubs.keys()), event)
+ nextsubs = dict()
+
+ # Scan whatever may be left over.
+ if len(nextsubs) > 0:
+ self.tryHostWrapper(list(nextsubs.keys()), event)
+
+
+# End of sfp_dnsbrute class
diff --git a/spiderfoot/modules/sfp_dnscommonsrv.py b/spiderfoot/modules/sfp_dnscommonsrv.py
new file mode 100644
index 0000000000000000000000000000000000000000..072d1320f19d1f7e12eefd8188ea09efce7e6863
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnscommonsrv.py
@@ -0,0 +1,159 @@
+# -*- coding: utf-8 -*-
+# -----------------------------------------------------------------------------
+# Name: sfp_dnscommonsrv
+# Purpose: SpiderFoot plug-in for attempting to resolve through
+# brute-forcing common DNS SRV records.
+#
+# Author: Michael Scherer
+#
+# Created: 22/08/2017
+# Copyright: (c) Michael Scherer 2017
+# Licence: MIT
+# -----------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnscommonsrv(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Common SRV",
+ 'summary': "Attempts to identify hostnames through brute-forcing common DNS SRV records.",
+ 'flags': ["slow"],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["DNS"]
+ }
+
+ opts = {}
+
+ optdescs = {}
+
+ events = None
+
+ commonsrv = [
+ # LDAP/Kerberos, used for Active Directory
+ # https://technet.microsoft.com/en-us/library/cc961719.aspx
+ '_ldap._tcp',
+ '_gc._msdcs',
+ '_ldap._tcp.pdc._msdcs',
+ '_ldap._tcp.gc._msdcs',
+ '_kerberos._tcp.dc._msdcs',
+ '_kerberos._tcp',
+ '_kerberos._udp',
+ '_kerberos-master._tcp',
+ '_kerberos-master._udp',
+ '_kpasswd._tcp',
+ '_kpasswd._udp',
+ '_ntp._udp',
+
+ # SIP
+ '_sip._tcp',
+ '_sip._udp',
+ '_sip._tls',
+ '_sips._tcp',
+
+ # STUN
+ # https://tools.ietf.org/html/rfc5389
+ '_stun._tcp',
+ '_stun._udp',
+ '_stuns._tcp',
+
+ # TURN
+ # https://tools.ietf.org/html/rfc5928
+ '_turn._tcp',
+ '_turn._udp',
+ '_turns._tcp',
+
+ # XMPP
+ # http://xmpp.org/rfcs/rfc6120.html
+ '_jabber._tcp',
+ '_xmpp-client._tcp',
+ '_xmpp-server._tcp'
+ ]
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.events = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['INTERNET_NAME', 'DOMAIN_NAME']
+
+ def producedEvents(self):
+ return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == "sfp_dnscommonsrv":
+ self.debug(f"Ignoring {eventName}, from self.")
+ return
+
+ eventDataHash = self.sf.hashstring(eventData)
+ parentEvent = event
+
+ if eventDataHash in self.events:
+ return
+
+ self.events[eventDataHash] = True
+
+ res = dns.resolver.Resolver()
+ if self.opts.get('_dnsserver', "") != "":
+ res.nameservers = [self.opts['_dnsserver']]
+
+ self.debug("Iterating through possible SRV records.")
+
+ # Try resolving common names
+ for srv in self.commonsrv:
+ if self.checkForStop():
+ return
+
+ name = srv + "." + eventData
+
+ # Skip hosts we've processed already
+ if self.sf.hashstring(name) in self.events:
+ continue
+
+ try:
+ answers = res.query(name, 'SRV', timeout=10)
+ except Exception:
+ answers = []
+
+ if not answers:
+ continue
+
+ evt = SpiderFootEvent(
+ "DNS_SRV",
+ name,
+ self.__name__,
+ parentEvent
+ )
+ self.notifyListeners(evt)
+
+ for a in answers:
+ # Strip off the trailing .
+ tgt_clean = a.target.to_text().rstrip(".")
+
+ if self.getTarget().matches(tgt_clean):
+ evt_type = "INTERNET_NAME"
+ else:
+ evt_type = "AFFILIATE_INTERNET_NAME"
+
+ evt = SpiderFootEvent(
+ evt_type,
+ tgt_clean,
+ self.__name__,
+ parentEvent
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_dnscommonsrv class
diff --git a/spiderfoot/modules/sfp_dnsdb.py b/spiderfoot/modules/sfp_dnsdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f0130a6ecff2aaf26c91fcc0977717b01ed9231
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsdb.py
@@ -0,0 +1,333 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsdb
+# Purpose: SpiderFoot plug-in that resolves and gets history of domains and IPs
+#
+# Author: Filip Aleksić
+#
+# Created: 2020-09-09
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsdb(SpiderFootPlugin):
+ meta = {
+ "name": "DNSDB",
+ "summary": "Query FarSight's DNSDB for historical and passive DNS data.",
+ 'flags': ["apikey"],
+ "useCases": ["Passive", "Footprint", "Investigate"],
+ "categories": ["Passive DNS"],
+ "dataSource": {
+ "website": "https://www.farsightsecurity.com",
+ "model": "FREE_AUTH_LIMITED",
+ "references": [
+ "https://docs.dnsdb.info/dnsdb-apiv2/",
+ "https://www.farsightsecurity.com/get-started/"
+ "https://www.farsightsecurity.com/solutions/dnsdb/",
+ ],
+ "apiKeyInstructions": [
+ "Visit https://www.farsightsecurity.com/get-started/",
+ "Select the model that best fit your needs (free or premium)",
+ "Fill in the form to get API key",
+ "Check your email for your API Key ",
+ ],
+ "favIcon": "https://www.farsightsecurity.com/favicon.ico",
+ "logo": "https://www.farsightsecurity.com/assets/media/svg/farsight-logo.svg",
+ "description": "Farsight Security’s DNSDB is the world’s largest "
+ "database of DNS resolution and change data. Started in 2010 and "
+ "updated in real-time, DNSDB provides the most comprehensive "
+ "history of domains and IP addresses worldwide.",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ "age_limit_days": 0,
+ "verify": True,
+ "cohostsamedomain": False,
+ "maxcohost": 100,
+ }
+
+ optdescs = {
+ "api_key": "DNSDB API Key.",
+ "age_limit_days": "Ignore any DNSDB records older than this many days. 0 = unlimited.",
+ "verify": "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ "cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",
+ "maxcohost": "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "IPV6_ADDRESS", "DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "RAW_RIR_DATA",
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "PROVIDER_DNS",
+ "DNS_TEXT",
+ "PROVIDER_MAIL",
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "CO_HOSTED_SITE",
+ ]
+
+ def query(self, endpoint, queryType, query):
+ if endpoint not in ("rrset", "rdata"):
+ self.error(f"Endpoint MUST be rrset or rdata, you sent {endpoint}")
+ return None
+
+ if queryType not in ("name", "ip"):
+ self.error(f"Query type MUST be name or ip, you sent {queryType}")
+ return None
+
+ headers = {"Accept": "application/x-ndjson", "X-API-Key": self.opts["api_key"]}
+
+ res = self.sf.fetchUrl(
+ f"https://api.dnsdb.info/dnsdb/v2/lookup/{endpoint}/{queryType}/{query}",
+ timeout=30,
+ useragent="SpiderFoot",
+ headers=headers,
+ )
+
+ if res["code"] == "429":
+ self.error("You are being rate-limited by DNSDB")
+ self.errorState = True
+ return None
+
+ if res["content"] is None:
+ self.info(f"No DNSDB record found for {query}")
+ return None
+
+ splittedContent = res["content"].strip().split("\n")
+ if len(splittedContent) == 2:
+ self.info(f"No DNSDB record found for {query}")
+ return None
+
+ if len(splittedContent) < 2:
+ self.info(f"Unexpected DNSDB response {query}")
+ return None
+
+ try:
+ records = []
+ for content in splittedContent:
+ records.append(json.loads(content))
+ except json.JSONDecodeError as e:
+ self.error(f"Error processing JSON response from DNSDB: {e}")
+ return None
+
+ return records[1:-1]
+
+ def isTooOld(self, lastSeen):
+ ageLimitTs = int(time.time()) - (86400 * self.opts["age_limit_days"])
+ if self.opts["age_limit_days"] > 0 and lastSeen < ageLimitTs:
+ self.debug("Record found but too old, skipping.")
+ return True
+ return False
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error("You enabled sfp_dnsdb but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+ self.results[eventData] = True
+
+ responseData = set()
+ coHosts = set()
+
+ if eventName == "DOMAIN_NAME":
+ rrsetRecords = self.query("rrset", "name", eventData)
+ if rrsetRecords is None:
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(rrsetRecords), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for record in rrsetRecords:
+ record = record.get("obj")
+ if self.checkForStop():
+ return
+
+ if self.isTooOld(record.get("time_last", 0)):
+ continue
+
+ if record.get("rrtype") not in (
+ "A",
+ "AAAA",
+ "MX",
+ "NS",
+ "TXT",
+ "CNAME",
+ ):
+ continue
+
+ for data in record.get("rdata"):
+ data = data.rstrip(".")
+ if data in responseData:
+ continue
+ responseData.add(data)
+
+ if record.get("rrtype") == "A":
+ if not self.sf.validIP(data):
+ self.debug(f"Skipping invalid IP address {data}")
+ continue
+
+ if self.opts["verify"] and not self.sf.validateIP(
+ eventData, data
+ ):
+ self.debug(
+ f"Host {eventData} no longer resolves to {data}"
+ )
+ continue
+
+ evt = SpiderFootEvent("IP_ADDRESS", data, self.__name__, event)
+
+ if record.get("rrtype") == "AAAA":
+
+ if not self.getTarget().matches(
+ data, includeChildren=True, includeParents=True
+ ):
+ continue
+
+ if not self.sf.validIP6(data):
+ self.debug("Skipping invalid IPv6 address " + data)
+ continue
+
+ if self.opts["verify"] and not self.sf.validateIP(
+ eventData, data
+ ):
+ self.debug(
+ "Host " + eventData + " no longer resolves to " + data
+ )
+ continue
+
+ evt = SpiderFootEvent("IPV6_ADDRESS", data, self.__name__, event)
+ elif record.get("rrtype") == "MX":
+ data = re.sub(r'.*\s+(.*)', r'\1', data)
+ evt = SpiderFootEvent("PROVIDER_MAIL", data, self.__name__, event)
+ elif record.get("rrtype") == "NS":
+ evt = SpiderFootEvent("PROVIDER_DNS", data, self.__name__, event)
+ elif record.get("rrtype") == "TXT":
+ data = data.replace('"', '')
+ evt = SpiderFootEvent("DNS_TEXT", data, self.__name__, event)
+ elif record.get("rrtype") == "CNAME":
+ if not self.getTarget().matches(data):
+ coHosts.add(data)
+
+ self.notifyListeners(evt)
+
+ rdataRecords = self.query("rdata", "name", eventData)
+
+ if rdataRecords is None:
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(rdataRecords), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for record in rdataRecords:
+ record = record.get("obj")
+ if self.isTooOld(record.get("time_last", 0)):
+ continue
+
+ if record.get("rrtype") not in ("NS", "CNAME"):
+ continue
+ data = record.get("rrname").rstrip(".")
+
+ if data in responseData:
+ continue
+ responseData.add(data)
+ if record.get("rrtype") == "NS":
+ evt = SpiderFootEvent("PROVIDER_DNS", data, self.__name__, event)
+ elif record.get("rrtype") == "CNAME":
+ if not self.getTarget().matches(data):
+ coHosts.add(data)
+
+ elif eventName in ("IP_ADDRESS", "IPV6_ADDRESS"):
+ rdataRecords = self.query("rdata", "ip", eventData)
+ if rdataRecords is None:
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(rdataRecords), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for record in rdataRecords:
+ record = record.get("obj")
+ if self.checkForStop():
+ return
+
+ if self.isTooOld(record.get("time_last", 0)):
+ continue
+
+ if record.get("rrtype") not in ("A", "AAAA"):
+ continue
+
+ data = record.get("rrname").rstrip(".")
+
+ if data in responseData:
+ continue
+ responseData.add(data)
+
+ if not self.getTarget().matches(data):
+ coHosts.add(data)
+ continue
+
+ if self.opts["verify"] and not self.sf.resolveHost(data) and not self.sf.resolveHost6(data):
+ self.debug(f"Host {data} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", data, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("INTERNET_NAME", data, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for co in coHosts:
+ if eventName == "IP_ADDRESS" and (
+ self.opts["verify"] and not self.sf.validateIP(co, eventData)
+ ):
+ self.debug("Host no longer resolves to our IP.")
+ continue
+
+ if not self.opts["cohostsamedomain"]:
+ if self.getTarget().matches(co, includeParents=True):
+ self.debug(
+ "Skipping " + co + " because it is on the same domain."
+ )
+ continue
+
+ if self.cohostcount < self.opts["maxcohost"]:
+ evt = SpiderFootEvent("CO_HOSTED_SITE", co, self.__name__, event)
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+
+# End of sfp_dnsdb class
diff --git a/spiderfoot/modules/sfp_dnsdumpster.py b/spiderfoot/modules/sfp_dnsdumpster.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ef5b3af1490ee1917b9e9c70071f2e8988cbed0
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsdumpster.py
@@ -0,0 +1,143 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsdumpster
+# Purpose: SpiderFoot plug-in for subdomain enumeration using
+# dnsdumpster.com
+#
+# Author: TheTechromancer
+#
+# Created: 05/21/2021
+# Copyright: (c) Steve Micallef 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from bs4 import BeautifulSoup
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsdumpster(SpiderFootPlugin):
+
+ meta = {
+ "name": "DNSDumpster",
+ "summary": "Passive subdomain enumeration using HackerTarget's DNSDumpster",
+ "useCases": ["Investigate", "Footprint", "Passive"],
+ "categories": ["Passive DNS"],
+ "dataSource": {
+ "website": "https://dnsdumpster.com/",
+ "model": "FREE_NOAUTH_UNLIMITED",
+ "description": "DNSdumpster.com is a FREE domain research tool that can discover hosts related to a domain.",
+ }
+ }
+
+ # Default options
+ opts = {}
+
+ # Option descriptions
+ optdescs = {}
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.debug("Setting up sfp_dnsdumpster")
+ self.results = self.tempStorage()
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "INTERNET_NAME"]
+
+ def producedEvents(self):
+ return ["INTERNET_NAME", "INTERNET_NAME_UNRESOLVED"]
+
+ def query(self, domain):
+ ret = []
+ # first, get the CSRF tokens
+ url = "https://dnsdumpster.com"
+ res1 = self.sf.fetchUrl(
+ url,
+ useragent=self.opts.get("_useragent", "Spiderfoot")
+ )
+ if res1["code"] not in ["200"]:
+ self.error(f"Bad response code \"{res1['code']}\" from DNSDumpster")
+ else:
+ self.debug(f"Valid response code \"{res1['code']}\" from DNSDumpster")
+ html = BeautifulSoup(str(res1["content"]), features="lxml")
+ csrftoken = None
+ csrfmiddlewaretoken = None
+ try:
+ for cookie in res1["headers"].get("set-cookie", "").split(";"):
+ k, v = cookie.split('=', 1)
+ if k == "csrftoken":
+ csrftoken = str(v)
+ csrfmiddlewaretoken = html.find("input", {"name": "csrfmiddlewaretoken"}).attrs.get("value", None)
+ except Exception:
+ pass
+
+ # Abort if we didn't get the tokens
+ if not csrftoken or not csrfmiddlewaretoken:
+ self.error("Error obtaining CSRF tokens")
+ self.errorState = True
+ return ret
+
+ self.debug("Successfully obtained CSRF tokens")
+
+ # Otherwise, do the needful
+ url = "https://dnsdumpster.com/"
+ subdomains = set()
+ res2 = self.sf.fetchUrl(
+ url,
+ cookies={
+ "csrftoken": csrftoken
+ },
+ postData={
+ "csrfmiddlewaretoken": csrfmiddlewaretoken,
+ "targetip": str(domain).lower(),
+ "user": "free"
+ },
+ headers={
+ "origin": "https://dnsdumpster.com",
+ "referer": "https://dnsdumpster.com/"
+ },
+ useragent=self.opts.get("_useragent", "Spiderfoot")
+ )
+ if res2["code"] not in ["200"]:
+ self.error(f"Bad response code \"{res2['code']}\" from DNSDumpster")
+ return ret
+
+ html = BeautifulSoup(str(res2["content"]), features="lxml")
+ escaped_domain = re.escape(domain)
+ match_pattern = re.compile(r"^[\w\.-]+\." + escaped_domain + r"$")
+ for subdomain in html.findAll(text=match_pattern):
+ subdomains.add(str(subdomain).strip().lower())
+
+ return list(subdomains)
+
+ def sendEvent(self, source, host):
+ if self.sf.resolveHost(host) or self.sf.resolveHost6(host):
+ e = SpiderFootEvent("INTERNET_NAME", host, self.__name__, source)
+ else:
+ e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, source)
+ self.notifyListeners(e)
+
+ def handleEvent(self, event):
+ query = str(event.data).lower()
+
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ # skip if we've already processed this event (or its parent domain/subdomain)
+ target = self.getTarget()
+ eventDataHash = self.sf.hashstring(query)
+ if eventDataHash in self.results or \
+ (target.matches(query, includeParents=True) and not
+ target.matches(query, includeChildren=False)):
+ self.debug(f"Skipping already-processed event, {event.eventType}, from {event.module}")
+ return
+ self.results[eventDataHash] = True
+
+ for hostname in self.query(query):
+ if target.matches(hostname, includeParents=True) and not \
+ target.matches(hostname, includeChildren=False):
+ self.sendEvent(event, hostname)
+ else:
+ self.debug(f"Invalid subdomain: {hostname}")
diff --git a/spiderfoot/modules/sfp_dnsgrep.py b/spiderfoot/modules/sfp_dnsgrep.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b09af8f5926f3afc9b1fac51dc4db41ed4dd9df
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsgrep.py
@@ -0,0 +1,170 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsgrep
+# Purpose: SpiderFoot plug-in for retrieving domain names
+# from Rapid7 Sonar Project data sets using DNSGrep API.
+# - https://opendata.rapid7.com/about/
+# - https://blog.erbbysam.com/index.php/2019/02/09/dnsgrep/
+# - https://github.com/erbbysam/DNSGrep
+#
+# Author:
+#
+# Created: 2020-03-14
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsgrep(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNSGrep",
+ 'summary': "Obtain Passive DNS information from Rapid7 Sonar Project using DNSGrep API.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://opendata.rapid7.com/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://opendata.rapid7.com/apihelp/",
+ "https://www.rapid7.com/about/research"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://opendata.rapid7.com/apihelp/",
+ "Submit form requesting for access",
+ "After getting access, navigate to https://insight.rapid7.com/platform#/apiKeyManagement",
+ "Create an User Key",
+ "The API key will be listed after creation"
+ ],
+ 'favIcon': "https://www.rapid7.com/includes/img/favicon.ico",
+ 'logo': "https://www.rapid7.com/includes/img/Rapid7_logo.svg",
+ 'description': "Offering researchers and community members open access to data from Project Sonar, "
+ "which conducts internet-wide surveys to gain insights into global exposure "
+ "to common vulnerabilities.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'timeout': 30,
+ 'dns_resolve': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'timeout': "Query timeout, in seconds.",
+ 'dns_resolve': "DNS resolve each identified domain."
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["INTERNET_NAME", "INTERNET_NAME_UNRESOLVED", "RAW_RIR_DATA"]
+
+ # Query the DNSGrep REST API
+ def query(self, qry):
+ params = {
+ 'q': '.' + qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+
+ res = self.sf.fetchUrl('https://dns.bufferover.run/dns?' + urllib.parse.urlencode(params),
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.info("No results found for " + qry)
+ return None
+
+ if res['code'] != '200':
+ self.debug("Error retrieving search results for " + qry)
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from DNSGrep: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ data = self.query(eventData)
+
+ if data is None:
+ self.info("No DNS records found for " + eventData)
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ domains = list()
+
+ # Forward DNS A records
+ fdns = data.get("FDNS_A")
+ if fdns:
+ for r in fdns:
+ try:
+ ip, domain = r.split(',')
+ except Exception:
+ continue
+
+ domains.append(domain)
+
+ # Reverse DNS records
+ rdns = data.get("RDNS")
+ if rdns:
+ for r in rdns:
+ try:
+ ip, domain = r.split(',')
+ except Exception:
+ continue
+
+ domains.append(domain)
+
+ for domain in domains:
+ if domain in self.results:
+ continue
+
+ if not self.getTarget().matches(domain, includeParents=True):
+ continue
+
+ evt_type = "INTERNET_NAME"
+
+ if self.opts["dns_resolve"] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt_type += "_UNRESOLVED"
+
+ evt = SpiderFootEvent(evt_type, domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_dnsgrep class
diff --git a/spiderfoot/modules/sfp_dnsneighbor.py b/spiderfoot/modules/sfp_dnsneighbor.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe90bd6dba273335b78dc0d046c30cddd55eb519
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsneighbor.py
@@ -0,0 +1,198 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsneighbor
+# Purpose: SpiderFoot plug-in for gathering IP addresses from sub-domains
+# and hostnames identified, and optionally affiliates.
+#
+# Author: Steve Micallef
+#
+# Created: 07/07/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import ipaddress
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsneighbor(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Look-aside",
+ 'summary': "Attempt to reverse-resolve the IP addresses next to your target to see if they are related.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["DNS"]
+ }
+
+ # Default options
+ opts = {
+ 'lookasidebits': 4,
+ 'validatereverse': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",
+ 'lookasidebits': "If look-aside is enabled, the netmask size (in CIDR notation) to check. Default is 4 bits (16 hosts)."
+ }
+
+ events = None
+ domresults = None
+ hostresults = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.events = self.tempStorage()
+ self.domresults = self.tempStorage()
+ self.hostresults = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["AFFILIATE_IPADDR", "IP_ADDRESS"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventDataHash = self.sf.hashstring(eventData)
+ addrs = None
+ parentEvent = event
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventDataHash in self.events:
+ return
+
+ self.events[eventDataHash] = True
+
+ try:
+ address = ipaddress.ip_address(eventData)
+ netmask = address.max_prefixlen - min(address.max_prefixlen, max(1, int(self.opts.get("lookasidebits"))))
+ network = ipaddress.ip_network(f"{eventData}/{netmask}", strict=False)
+ except ValueError:
+ self.error(f"Invalid IP address received: {eventData}")
+ return
+
+ self.debug(f"Lookaside max: {network.network_address}, min: {network.broadcast_address}")
+
+ for ip in network:
+ sip = str(ip)
+ self.debug("Attempting look-aside lookup of: " + sip)
+ if self.checkForStop():
+ return
+
+ if sip in self.hostresults or sip == eventData:
+ continue
+
+ addrs = self.sf.resolveIP(sip)
+ if not addrs:
+ self.debug("Look-aside resolve for " + sip + " failed.")
+ continue
+
+ # Report addresses that resolve to hostnames on the same
+ # domain or sub-domain as the target.
+ if self.getTarget().matches(sip):
+ affil = False
+ else:
+ affil = True
+ for a in addrs:
+ if self.getTarget().matches(a):
+ affil = False
+
+ # Generate the event for the look-aside IP, but don't let it re-trigger
+ # this module by adding it to self.events first.
+ self.events[sip] = True
+ ev = self.processHost(sip, parentEvent, affil)
+
+ if not ev:
+ continue
+
+ for addr in addrs:
+ if self.checkForStop():
+ return
+
+ if addr == sip:
+ continue
+
+ if self.sf.validIP(addr) or self.sf.validIP6(addr):
+ parent = parentEvent
+ else:
+ # Hostnames from the IP need to be linked to the IP
+ parent = ev
+
+ if self.getTarget().matches(addr):
+ # Generate an event for the IP, then
+ # let the handling by this module take
+ # care of follow-up processing.
+ self.processHost(addr, parent, False)
+ else:
+ self.processHost(addr, parent, True)
+
+ def processHost(self, host, parentEvent, affiliate=None):
+ parentHash = self.sf.hashstring(parentEvent.data)
+ if host not in self.hostresults:
+ self.hostresults[host] = [parentHash]
+ else:
+ if parentHash in self.hostresults[host] or parentEvent.data == host:
+ self.debug("Skipping host, " + host + ", already processed.")
+ return None
+ self.hostresults[host] = self.hostresults[host] + [parentHash]
+
+ self.debug("Found host: " + host)
+ # If the returned hostname is aliased to our
+ # target in some way, flag it as an affiliate
+ if affiliate is None:
+ affil = True
+ if self.getTarget().matches(host):
+ affil = False
+ else:
+ # If the IP the host resolves to is in our
+ # list of aliases,
+ if not self.sf.validIP(host) and not self.sf.validIP6(host):
+ hostips = self.sf.resolveHost(host)
+ if hostips:
+ for hostip in hostips:
+ if self.getTarget().matches(hostip):
+ affil = False
+ break
+ hostips6 = self.sf.resolveHost6(host)
+ if hostips6:
+ for hostip in hostips6:
+ if self.getTarget().matches(hostip):
+ affil = False
+ break
+ else:
+ affil = affiliate
+
+ if not self.sf.validIP(host):
+ return None
+
+ if affil:
+ htype = "AFFILIATE_IPADDR"
+ else:
+ htype = "IP_ADDRESS"
+
+ # If names were found, leave them to sfp_dnsresolve to resolve
+ if not htype:
+ return None
+
+ # Report the host
+ evt = SpiderFootEvent(htype, host, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ return evt
+
+# End of sfp_dnsneighbor class
diff --git a/spiderfoot/modules/sfp_dnsraw.py b/spiderfoot/modules/sfp_dnsraw.py
new file mode 100644
index 0000000000000000000000000000000000000000..174ac3d86836cf335e911183cd116ddd2f1a1133
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsraw.py
@@ -0,0 +1,179 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsraw
+# Purpose: SpiderFoot plug-in for collecting raw DNS records.
+# Also extracts hostnames from SPF records.
+#
+# Author: Steve Micallef
+#
+# Created: 07/07/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+import dns.query
+import dns.rdatatype
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsraw(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Raw Records",
+ 'summary': "Retrieves raw DNS records such as MX, TXT and others.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["DNS"]
+ }
+
+ # Default options
+ opts = {
+ 'verify': True,
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'verify': "Verify identified hostnames resolve."
+ }
+
+ events = None
+ checked = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.events = self.tempStorage()
+ self.checked = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['INTERNET_NAME', 'DOMAIN_NAME', 'DOMAIN_NAME_PARENT']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["PROVIDER_MAIL", "PROVIDER_DNS", "RAW_DNS_RECORDS", "DNS_TEXT", "DNS_SPF",
+ 'INTERNET_NAME', 'INTERNET_NAME_UNRESOLVED',
+ 'AFFILIATE_INTERNET_NAME', 'AFFILIATE_INTERNET_NAME_UNRESOLVED']
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventDataHash = self.sf.hashstring(eventData)
+ parentEvent = event
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventDataHash in self.events:
+ self.debug("Skipping duplicate event for " + eventData)
+ return
+
+ self.events[eventDataHash] = True
+
+ self.debug("Gathering DNS records for " + eventData)
+
+ domains = list()
+
+ # Process the raw data alone
+ recs = {
+ 'CNAME': r'\S+\s+(?:\d+)?\s+IN\s+CNAME\s+(\S+)\.',
+ 'MX': r'\S+\s+(?:\d+)?\s+IN\s+MX\s+\d+\s+(\S+)\.',
+ 'NS': r'\S+\s+(?:\d+)?\s+IN\s+NS\s+(\S+)\.',
+ 'TXT': r'\S+\s+TXT\s+\"(.[^\"]*)"'
+ }
+
+ for rec in list(recs.keys()):
+ if self.checkForStop():
+ return
+
+ try:
+ req = dns.message.make_query(eventData, dns.rdatatype.from_text(rec))
+
+ if self.opts.get('_dnsserver', "") != "":
+ n = self.opts['_dnsserver']
+ else:
+ ns = dns.resolver.get_default_resolver()
+ n = ns.nameservers[0]
+
+ res = dns.query.udp(req, n, timeout=30)
+
+ if not len(res.answer):
+ continue
+ except Exception as e:
+ self.error(f"Failed to obtain DNS response for {eventData} ({e})")
+ continue
+
+ # Iterate through DNS answers
+ for x in res.answer:
+ if str(x) in self.checked:
+ continue
+
+ self.checked[str(x)] = True
+
+ evt = SpiderFootEvent("RAW_DNS_RECORDS", str(x), self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ for rx in list(recs.keys()):
+ self.debug("Checking " + str(x) + " + against " + recs[rx])
+ pat = re.compile(recs[rx], re.IGNORECASE | re.DOTALL)
+ grps = re.findall(pat, str(x))
+
+ if len(grps) == 0:
+ continue
+
+ for m in grps:
+ self.debug("Matched: " + m)
+ strdata = str(m)
+
+ if rx == "CNAME":
+ domains.append(strdata.lower())
+
+ if rx == "MX":
+ evt = SpiderFootEvent("PROVIDER_MAIL", strdata.lower(), self.__name__, parentEvent)
+ self.notifyListeners(evt)
+ domains.append(strdata.lower())
+
+ if rx == "NS":
+ evt = SpiderFootEvent("PROVIDER_DNS", strdata.lower(), self.__name__, parentEvent)
+ self.notifyListeners(evt)
+ domains.append(strdata.lower())
+
+ if rx == "TXT":
+ evt = SpiderFootEvent("DNS_TEXT", strdata, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ if "v=spf" in strdata or "spf2.0/" in strdata:
+ evt = SpiderFootEvent("DNS_SPF", strdata, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ matches = re.findall(r'include:(.+?) ', strdata, re.IGNORECASE | re.DOTALL)
+ if matches:
+ for domain in matches:
+ if '_' in domain:
+ continue
+ domains.append(domain.lower())
+
+ for domain in set(domains):
+ if self.getTarget().matches(domain, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ else:
+ evt_type = 'AFFILIATE_INTERNET_NAME'
+
+ if self.opts['verify'] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt_type += '_UNRESOLVED'
+
+ evt = SpiderFootEvent(evt_type, domain, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+# End of sfp_dnsraw class
diff --git a/spiderfoot/modules/sfp_dnsresolve.py b/spiderfoot/modules/sfp_dnsresolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..082cf92b3cfe012d87c9840d57698aa0d7f18a2f
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnsresolve.py
@@ -0,0 +1,541 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnsresolve
+# Purpose: SpiderFoot plug-in for extracting hostnames from identified data
+# and resolving them.
+#
+# Author: Steve Micallef
+#
+# Created: 07/07/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+import urllib
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnsresolve(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Resolver",
+ 'summary': "Resolves hosts and IP addresses identified, also extracted from raw content.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["DNS"]
+ }
+
+ # Default options
+ opts = {
+ 'validatereverse': True,
+ 'skipcommononwildcard': True,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxv6netblock': 120,
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'skipcommononwildcard': "If wildcard DNS is detected, only attempt to look up the first common sub-domain from the common sub-domain list.",
+ 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "Maximum owned IPv4 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6netblock': "Maximum owned IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
+ }
+
+ events = None
+ domresults = None
+ hostresults = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.events = self.tempStorage()
+ self.domresults = self.tempStorage()
+ self.hostresults = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def enrichTarget(self, target):
+ ret = list()
+ # If it's an IP, get the hostname it reverse resolves to
+ self.info("Identifying aliases for specified target(s)")
+ ret = self.resolveTargets(target, self.opts['validatereverse'])
+ if not ret:
+ return target
+
+ for host in ret:
+ self.debug("Found an alias: " + host)
+ if self.sf.validIP(host):
+ target.setAlias(host, "IP_ADDRESS")
+ elif self.sf.validIP6(host):
+ target.setAlias(host, "IPV6_ADDRESS")
+ else:
+ target.setAlias(host, "INTERNET_NAME")
+ idnahost = host.encode("idna")
+ if idnahost != host:
+ target.setAlias(idnahost.decode('ascii', errors='replace'), "INTERNET_NAME")
+
+ # If the target was a hostname/sub-domain, we can
+ # add the domain as an alias for the target. But
+ # not if the target was an IP or subnet.
+ # if target.targetType == "INTERNET_NAME":
+ # dom = self.sf.hostDomain(host, self.opts['_internettlds'])
+ # target.setAlias(dom, "INTERNET_NAME")
+
+ self.info(f"Target aliases identified: {target.targetAliases}")
+
+ return target
+
+ def resolveTargets(self, target, validateReverse: bool) -> list:
+ """Resolve alternative names for a given target.
+
+ Args:
+ target (SpiderFootTarget): target object
+ validateReverse (bool): validate domain names resolve
+
+ Returns:
+ list: list of domain names and IP addresses
+ """
+ ret = list()
+
+ if not target:
+ return ret
+
+ t = target.targetType
+ v = target.targetValue
+
+ if t in ["IP_ADDRESS", "IPV6_ADDRESS"]:
+ r = self.sf.resolveIP(v)
+ if r:
+ ret.extend(r)
+ if t == "INTERNET_NAME":
+ r = self.sf.resolveHost(v)
+ if r:
+ ret.extend(r)
+ r = self.sf.resolveHost6(v)
+ if r:
+ ret.extend(r)
+ if t == "NETBLOCK_OWNER":
+ max_netblock = self.opts['maxnetblock']
+ if IPNetwork(v).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(v).prefixlen} > {max_netblock}")
+ return list(set(ret))
+
+ for addr in IPNetwork(v):
+ if self.checkForStop():
+ return list(set(ret))
+
+ ipaddr = str(addr)
+ if ipaddr.split(".")[3] in ['255', '0']:
+ continue
+
+ if '255' in ipaddr.split("."):
+ continue
+
+ ret.append(ipaddr)
+
+ # Add the reverse-resolved hostnames as aliases too
+ names = self.sf.resolveIP(ipaddr)
+ if not names:
+ continue
+
+ if not validateReverse:
+ ret.extend(names)
+ continue
+
+ for host in names:
+ chk = self.sf.resolveHost(host)
+ if chk and ipaddr in chk:
+ ret.append(host)
+ if t == "NETBLOCKV6_OWNER":
+ max_netblock = self.opts['maxv6netblock']
+ if IPNetwork(v).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(v).prefixlen} > {max_netblock}")
+ return list(set(ret))
+
+ for addr in IPNetwork(v):
+ if self.checkForStop():
+ return list(set(ret))
+
+ ipaddr = str(addr)
+
+ ret.append(ipaddr)
+
+ # Add the reverse-resolved hostnames as aliases too
+ names = self.sf.resolveIP(ipaddr)
+ if not names:
+ continue
+
+ if not validateReverse:
+ ret.extend(names)
+ continue
+
+ for host in names:
+ chk = self.sf.resolveHost6(host)
+ if chk and ipaddr in chk:
+ ret.append(host)
+
+ return list(set(ret))
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ # Events that need some kind of DNS treatment
+ "CO_HOSTED_SITE", "AFFILIATE_INTERNET_NAME", "NETBLOCK_OWNER", "NETBLOCKV6_OWNER",
+ "IP_ADDRESS", "IPV6_ADDRESS", "INTERNET_NAME", "AFFILIATE_IPADDR", "AFFILIATE_IPV6_ADDRESS",
+ # Events that may contain hostnames in their content
+ "TARGET_WEB_CONTENT", "BASE64_DATA", "AFFILIATE_DOMAIN_WHOIS",
+ "CO_HOSTED_SITE_DOMAIN_WHOIS", "DOMAIN_WHOIS", "NETBLOCK_WHOIS",
+ "LEAKSITE_CONTENT", "RAW_DNS_RECORDS", "RAW_FILE_META_DATA",
+ "RAW_RIR_DATA", "SIMILARDOMAIN_WHOIS",
+ "SSL_CERTIFICATE_RAW", "SSL_CERTIFICATE_ISSUED", "TCP_PORT_OPEN_BANNER",
+ "WEBSERVER_BANNER", "WEBSERVER_HTTPHEADERS"
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["IP_ADDRESS", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_IPADDR", "AFFILIATE_IPV6_ADDRESS", "DOMAIN_NAME", "IPV6_ADDRESS", "INTERNAL_IP_ADDRESS",
+ "DOMAIN_NAME_PARENT", "CO_HOSTED_SITE_DOMAIN", "AFFILIATE_DOMAIN_NAME",
+ "INTERNET_NAME_UNRESOLVED"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event) -> None:
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventDataHash = self.sf.hashstring(eventData)
+ addrs = None
+ parentEvent = event
+
+ # Don't be recursive for names
+ if srcModuleName in ["sfp_dnsresolve"] and "_NAME" in eventName:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventDataHash in self.events:
+ self.debug("Skipping duplicate event.")
+ return
+
+ self.events[eventDataHash] = True
+
+ # Parse Microsoft workaround "ipv6-literal.net" fake domain for IPv6 UNC paths
+ # For internal use on Windows systems (should not resolve in DNS)
+ if eventData.endswith(".ipv6-literal.net") and eventName == "AFFILIATE_INTERNET_NAME":
+ ipv6 = eventData.split(".ipv6-literal.net")[0].replace('-', ':').replace('s', '%').split('%')[0]
+ if self.sf.validIP6(ipv6):
+ if self.getTarget().matches(ipv6):
+ evt = SpiderFootEvent("IPV6_ADDRESS", ipv6, self.__name__, parentEvent)
+ else:
+ evt = SpiderFootEvent("AFFILIATE_IPV6_ADDRESS", ipv6, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+ return
+
+ # Convert ARPA in-addr.arpa address to IPv4 address
+ if eventData.endswith(".in-addr.arpa") and eventName == "AFFILIATE_INTERNET_NAME":
+ ipv4 = '.'.join(reversed(eventData.split('.in-addr.arpa')[0].split('.')))
+ if self.sf.validIP(ipv4):
+ if self.getTarget().matches(ipv4):
+ evt = SpiderFootEvent("IP_ADDRESS", ipv4, self.__name__, parentEvent)
+ else:
+ evt = SpiderFootEvent("AFFILIATE_IPADDR", ipv4, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ # Simply translates these to their domains
+ if eventName in ["CO_HOSTED_SITE", "AFFILIATE_INTERNET_NAME"]:
+ # If the co-host or affiliate is a domain name, generate
+ # a domain event.
+ if eventName == "AFFILIATE_INTERNET_NAME":
+ ev = "AFFILIATE_DOMAIN_NAME"
+ else:
+ ev = "CO_HOSTED_SITE_DOMAIN"
+
+ # What we've been provided might be a domain, so report it
+ if self.sf.isDomain(eventData, self.opts['_internettlds']):
+ evt = SpiderFootEvent(ev, eventData, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ # In case the domain of the provided host is different, report that too
+ dom = self.sf.hostDomain(eventData, self.opts['_internettlds'])
+ if dom and dom != eventData:
+ evt = SpiderFootEvent(ev, dom, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ # Resolve host names
+ if eventName in ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]:
+ addrs = list()
+ addrs.extend(self.sf.resolveHost(eventData))
+ addrs.extend(self.sf.resolveHost6(eventData))
+
+ if not addrs:
+ return
+
+ addrs.append(eventData)
+
+ # We now have a set of hosts/IPs to do something with.
+ for addr in set(addrs):
+ if self.checkForStop():
+ return
+
+ # IP addresses resolved from hosts are assumed
+ # to be part of the target (non-affiliates),
+ # unless the source event was an AFFILIATE event.
+ affiliate = False
+ if self.getTarget().matches(addr):
+ affiliate = False
+ elif eventName.startswith("AFFILIATE_"):
+ affiliate = True
+ self.processHost(addr, parentEvent, affiliate)
+
+ # Reverse resolve IP addresses
+ elif eventName in ["IP_ADDRESS", "IPV6_ADDRESS", "AFFILIATE_IPADDR", "AFFILIATE_IPV6_ADDRESS"]:
+ addrs = self.sf.resolveIP(eventData)
+
+ if not addrs:
+ return
+
+ addrs.append(eventData)
+
+ # We now have a set of hosts/IPs to do something with.
+ for addr in set(addrs):
+ if self.checkForStop():
+ return
+
+ # IP addresses resolved from hosts are assumed
+ # to be part of the target (non-affiliates),
+ # unless the source event was an AFFILIATE event.
+ affiliate = False
+ if self.getTarget().matches(addr):
+ affiliate = False
+ elif eventName.startswith("AFFILIATE_"):
+ affiliate = True
+ self.processHost(addr, parentEvent, affiliate)
+
+ elif eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts['netblocklookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_OWNER':
+ max_netblock = self.opts['maxv6netblock']
+ else:
+ max_netblock = self.opts['maxnetblock']
+
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ self.debug(f"Looking up IPs in owned netblock: {eventData}")
+ for ip in IPNetwork(eventData):
+ if self.checkForStop():
+ return
+
+ ipaddr = str(ip)
+
+ # Skip 0 and 255 for IPv4 addresses
+ if self.sf.validIP(ipaddr):
+ if ipaddr.split(".")[3] in ['255', '0']:
+ continue
+ if '255' in ipaddr.split("."):
+ continue
+
+ addrs = self.sf.resolveIP(ipaddr)
+ if not addrs:
+ continue
+
+ self.debug(f"Found {len(addrs)} reversed hostnames from {ipaddr} ({addrs})")
+ for addr in addrs:
+ if self.checkForStop():
+ return
+
+ # Generate an event for the IP, then
+ # let the handling by this module take
+ # care of follow-up processing.
+ self.processHost(addr, parentEvent, False)
+
+ # For everything else (ie, raw data), search for IPs/hosts
+ else:
+ # ignore co-hosted sites
+ if eventName == "CO_HOSTED_SITE":
+ return
+
+ data = urllib.parse.unquote(eventData).lower()
+ # We get literal \n from RAW_RIR_DATA in cases where JSON responses
+ # have been str()'d, breaking interpretation of hostnames.
+ if eventName == 'RAW_RIR_DATA':
+ data = re.sub(r'(\\x[0-f]{2}|\\n|\\r)', '\n', data)
+
+ for name in self.getTarget().getNames():
+ if self.checkForStop():
+ return
+
+ offset = data.find(name)
+ if offset < 0:
+ continue
+
+ pat = re.compile(r"[^a-z0-9\-\.]([a-z0-9\-\.]*\." + name + ")", re.DOTALL | re.MULTILINE)
+ while offset >= 0:
+ # If the target was found at the beginning of the content, skip past it
+ if offset == 0:
+ offset += len(name)
+ continue
+
+ if offset <= 100:
+ # Start from the beginning of the text
+ start = 0
+ else:
+ # Start looking for a host 100 chars before the target name
+ start = offset - 100
+
+ # Get up to 100 bytes before the name to try and get hostnames
+ chunkhost = data[start:(offset + start + len(name) + 1)]
+ matches = None
+ try:
+ matches = re.findall(pat, chunkhost)
+ except Exception as e:
+ self.error(f"Error applying regex to data ({e})")
+
+ if matches:
+ for match in matches:
+ # Wildcard certs will come in as .blah.blah
+ if match.startswith("."):
+ m = match[1:]
+ else:
+ m = match
+ self.processHost(m, parentEvent, False)
+
+ offset = data.find(name, start + len(chunkhost))
+
+ # Process a host/IP, parentEvent is the event that represents this entity
+ def processHost(self, host, parentEvent, affiliate=None) -> None:
+ parentHash = self.sf.hashstring(parentEvent.data)
+ if host in self.hostresults:
+ if parentHash in self.hostresults[host] or parentEvent.data == host:
+ self.debug(f"Skipping host, {host}, already processed.")
+ return
+ self.hostresults[host] = self.hostresults[host] + [parentHash]
+ else:
+ self.hostresults[host] = [parentHash]
+
+ self.debug(f"Found host: {host}")
+
+ # If the returned hostname is aliased to our
+ # target in some way, flag it as an affiliate
+ if affiliate is None:
+ affil = True
+ if self.getTarget().matches(host):
+ affil = False
+ # If the IP the host resolves to is in our
+ # list of aliases,
+ if not self.sf.validIP(host):
+ hostips = self.sf.resolveHost(host)
+ if hostips:
+ for hostip in hostips:
+ if self.getTarget().matches(hostip):
+ affil = False
+ break
+ hostips6 = self.sf.resolveHost6(host)
+ if hostips6:
+ for hostip6 in hostips6:
+ if self.getTarget().matches(hostip6):
+ affil = False
+ break
+ else:
+ affil = affiliate
+
+ if affil:
+ if self.sf.isValidLocalOrLoopbackIp(host):
+ htype = "INTERNAL_IP_ADDRESS"
+ elif self.sf.validIP(host):
+ htype = "AFFILIATE_IPADDR"
+ elif self.sf.validIP6(host):
+ htype = "AFFILIATE_IPV6_ADDRESS"
+ else:
+ htype = "AFFILIATE_INTERNET_NAME"
+ else:
+ if self.sf.isValidLocalOrLoopbackIp(host):
+ htype = "INTERNAL_IP_ADDRESS"
+ elif self.sf.validIP(host):
+ htype = "IP_ADDRESS"
+ elif self.sf.validIP6(host):
+ htype = "IPV6_ADDRESS"
+ else:
+ htype = "INTERNET_NAME"
+
+ if htype in ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]:
+ if not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ evt = SpiderFootEvent(f"{htype}_UNRESOLVED", host, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+ return
+
+ # Report the host
+ if host != parentEvent.data:
+ evt = SpiderFootEvent(htype, host, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+ else:
+ evt = parentEvent
+
+ if htype == "INTERNET_NAME":
+ dom = self.sf.hostDomain(host, self.opts['_internettlds'])
+ if dom:
+ self.processDomain(dom, evt, False, host)
+
+ # Try obtain the IPv6 address
+ ip6s = self.sf.resolveHost6(host)
+ if not ip6s:
+ return
+ for ip6 in ip6s:
+ parentHash = self.sf.hashstring(evt.data)
+ if ip6 not in self.hostresults:
+ self.hostresults[ip6] = [parentHash]
+ else:
+ if parentHash in self.hostresults[ip6] or evt.data == ip6:
+ self.debug(f"Skipping host, {ip6}, already processed.")
+ continue
+ self.hostresults[ip6] = self.hostresults[ip6] + [parentHash]
+
+ evt6 = SpiderFootEvent("IPV6_ADDRESS", ip6, self.__name__, evt)
+ self.notifyListeners(evt6)
+
+ if htype == "AFFILIATE_INTERNET_NAME":
+ dom = self.sf.hostDomain(host, self.opts['_internettlds'])
+ if not dom:
+ return
+ if dom == host and not self.sf.isDomain(dom, self.opts['_internettlds']):
+ return
+ self.processDomain(dom, evt, True, host)
+
+ def processDomain(self, domainName, parentEvent, affil=False, host=None) -> None:
+ if domainName in self.domresults:
+ self.debug(f"Skipping domain, {domainName}, already processed.")
+ return
+
+ self.domresults[domainName] = True
+
+ if affil:
+ domevt = SpiderFootEvent("AFFILIATE_DOMAIN_NAME", domainName,
+ self.__name__, parentEvent)
+ self.notifyListeners(domevt)
+ return
+
+ if self.getTarget().matches(domainName):
+ domevt = SpiderFootEvent("DOMAIN_NAME", domainName,
+ self.__name__, parentEvent)
+ self.notifyListeners(domevt)
+ else:
+ # Only makes sense to link this event with a source event
+ # that sits on the parent domain.
+ if not host:
+ return
+ if parentEvent.data.endswith("." + domainName):
+ domevt = SpiderFootEvent("DOMAIN_NAME_PARENT", domainName,
+ self.__name__, parentEvent)
+ self.notifyListeners(domevt)
+
+# End of sfp_dnsresolve class
diff --git a/spiderfoot/modules/sfp_dnszonexfer.py b/spiderfoot/modules/sfp_dnszonexfer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f693c7180d8106dc582a125ac903b8fca963b4f1
--- /dev/null
+++ b/spiderfoot/modules/sfp_dnszonexfer.py
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dnszonexfer
+# Purpose: SpiderFoot plug-in for attempting a DNS zone transfer.
+#
+# Author: Steve Micallef
+#
+# Created: 22/08/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+import dns.query
+import dns.zone
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dnszonexfer(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DNS Zone Transfer",
+ 'summary': "Attempts to perform a full DNS zone transfer.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["DNS"]
+ }
+
+ opts = {
+ "timeout": 30
+ }
+
+ optdescs = {
+ "timeout": "Timeout in seconds"
+ }
+
+ events = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.events = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['PROVIDER_DNS']
+
+ def producedEvents(self):
+ return ["RAW_DNS_RECORDS", "INTERNET_NAME"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ eventDataHash = self.sf.hashstring(eventData)
+ parentEvent = event
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == "sfp_dnszonexfer":
+ self.debug(f"Ignoring {eventName}, from self.")
+ return
+
+ if eventDataHash in self.events:
+ self.debug("Skipping duplicate event for " + eventData)
+ return
+
+ self.events[eventDataHash] = True
+
+ res = dns.resolver.Resolver()
+ if self.opts.get('_dnsserver', "") != "":
+ res.nameservers = [self.opts['_dnsserver']]
+
+ # Get the name server's IP. This is to avoid DNS leaks
+ # when attempting to resolve the name server during
+ # the zone transfer.
+ if not self.sf.validIP(eventData) and not self.sf.validIP6(eventData):
+ nsips = self.sf.resolveHost(eventData)
+ if not nsips:
+ return
+
+ if not nsips:
+ self.error("Couldn't resolve the name server, so not attempting zone transfer.")
+ return
+
+ for n in nsips:
+ if self.sf.validIP(n):
+ nsip = n
+ break
+ else:
+ nsip = eventData
+
+ for name in self.getTarget().getNames():
+ self.debug("Trying for name: " + name)
+ try:
+ ret = list()
+ z = dns.zone.from_xfr(dns.query.xfr(nsip, name, timeout=int(self.opts["timeout"])))
+ names = list(z.nodes.keys())
+ for n in names:
+ ret.append(z[n].to_text(n))
+
+ evt = SpiderFootEvent("RAW_DNS_RECORDS", "\n".join(ret), self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ # Try and pull out individual records
+ for row in ret:
+ pat = re.compile(r"^(\S+)\.?\s+\d+\s+IN\s+[AC].*", re.IGNORECASE | re.DOTALL)
+ grps = re.findall(pat, row)
+ if len(grps) > 0:
+ for strdata in grps:
+ self.debug("Matched: " + strdata)
+ if strdata.endswith("."):
+ strdata = strdata[:-1]
+ else:
+ strdata = strdata + "." + name
+
+ evt = SpiderFootEvent("INTERNET_NAME", strdata, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ except Exception as e:
+ self.info(f"Unable to perform DNS zone transfer for {eventData} ({name}): {e}")
+
+# End of sfp_dnszonexfer class
diff --git a/spiderfoot/modules/sfp_dronebl.py b/spiderfoot/modules/sfp_dronebl.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d7b42e4018d30b4f177cd728850d72145b4076f
--- /dev/null
+++ b/spiderfoot/modules/sfp_dronebl.py
@@ -0,0 +1,240 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_dronebl
+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains
+# appear in the DroneBL blocklist, indicating potential open-relays,
+# open proxies, malicious servers, vulnerable servers, etc.
+#
+# Author: Steve Micallef
+#
+# Created: 07/01/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_dronebl(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DroneBL",
+ 'summary': "Query the DroneBL database for open relays, open proxies, vulnerable servers, etc.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://dronebl.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://dronebl.org/docs/howtouse",
+ "https://dronebl.org/rpckey_signup",
+ "https://dronebl.org/docs/rpc2"
+ ],
+ 'favIcon': "https://dronebl.org/images/favicon.ico",
+ 'logo': "https://dronebl.org/images/dronebl-logo.svg",
+ 'description': "DroneBL is a realtime monitor of abusable IPs, which has "
+ "the goal of stopping abuse of infected machines.\n"
+ "A real-time tracker of abusable IPs.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'subnetlookup': True,
+ 'maxsubnet': 24
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
+ }
+
+ results = None
+
+ checks = {
+ "127.0.0.3": "dronebl.org - IRC Drone",
+ "127.0.0.5": "dronebl.org - Bottler",
+ "127.0.0.6": "dronebl.org - Unknown spambot or drone",
+ "127.0.0.7": "dronebl.org - DDOS Drone",
+ "127.0.0.8": "dronebl.org - SOCKS Proxy",
+ "127.0.0.9": "dronebl.org - HTTP Proxy",
+ "127.0.0.10": "dronebl.org - ProxyChain",
+ "127.0.0.11": "dronebl.org - Web Page Proxy",
+ "127.0.0.12": "dronebl.org - Open DNS Resolver",
+ "127.0.0.13": "dronebl.org - Brute force attackers",
+ "127.0.0.14": "dronebl.org - Open Wingate Proxy",
+ "127.0.0.15": "dronebl.org - Compromised router / gateway",
+ "127.0.0.16": "dronebl.org - Autorooting worms",
+ "127.0.0.17": "dronebl.org - Automatically determined botnet IPs (experimental)",
+ "127.0.0.18": "dronebl.org - Possibly compromised DNS/MX",
+ "127.0.0.19": "dronebl.org - Abused VPN Service",
+ "127.0.0.255": "dronebl.org - Unknown"
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'AFFILIATE_IPADDR',
+ 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER'
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ "VPN_HOST",
+ "PROXY_HOST"
+ ]
+
+ # Swap 1.2.3.4 to 4.3.2.1
+ def reverseAddr(self, ipaddr):
+ if not self.sf.validIP(ipaddr):
+ self.debug(f"Invalid IPv4 address {ipaddr}")
+ return None
+ return '.'.join(reversed(ipaddr.split('.')))
+
+ def queryAddr(self, qaddr):
+ """Query DroneBL DNS for an IPv4 address.
+
+ Args:
+ qaddr (str): IPv4 address.
+
+ Returns:
+ list: DroneBL DNS entries
+ """
+ if not self.sf.validIP(qaddr):
+ self.debug(f"Invalid IPv4 address {qaddr}")
+ return None
+
+ try:
+ lookup = self.reverseAddr(qaddr) + '.dnsbl.dronebl.org'
+ self.debug(f"Checking DroneBL blacklist: {lookup}")
+ return self.sf.resolveHost(lookup)
+ except Exception as e:
+ self.debug(f"DroneBL did not resolve {qaddr} / {lookup}: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'NETBLOCK_OWNER':
+ if not self.opts['netblocklookup']:
+ return
+
+ max_netblock = self.opts['maxnetblock']
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ if eventName == 'NETBLOCK_MEMBER':
+ if not self.opts['subnetlookup']:
+ return
+
+ max_subnet = self.opts['maxsubnet']
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ if eventName == "AFFILIATE_IPADDR":
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == "IP_ADDRESS":
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == "NETBLOCK_OWNER":
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == "NETBLOCK_MEMBER":
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ addrs = list()
+ if eventName.startswith("NETBLOCK_"):
+ for addr in IPNetwork(eventData):
+ addrs.append(str(addr))
+ else:
+ addrs.append(eventData)
+
+ for addr in addrs:
+ if self.checkForStop():
+ return
+
+ res = self.queryAddr(addr)
+
+ self.results[addr] = True
+
+ if not res:
+ continue
+
+ self.debug(f"{addr} found in DroneBL DNS: {res}")
+
+ for result in res:
+ k = str(result)
+ if k not in self.checks:
+ if not result.endswith('.dnsbl.dronebl.org'):
+ # This is an error. The "checks" dict may need to be updated.
+ self.error(f"DroneBL resolved address {addr} to unknown IP address {result} not found in DroneBL list.")
+ continue
+
+ evt = SpiderFootEvent(blacklist_type, f"{self.checks[k]} [{addr}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if k in [
+ "127.0.0.3",
+ "127.0.0.5",
+ "127.0.0.6",
+ "127.0.0.7",
+ "127.0.0.13",
+ "127.0.0.15",
+ "127.0.0.16",
+ "127.0.0.17",
+ "127.0.0.18",
+ "127.0.0.19",
+ ]:
+ evt = SpiderFootEvent(malicious_type, f"{self.checks[k]} [{addr}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if k in ["127.0.0.8", "127.0.0.9", "127.0.0.10", "127.0.0.11", "127.0.0.14"]:
+ evt = SpiderFootEvent("PROXY_HOST", addr, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if k == "127.0.0.19":
+ evt = SpiderFootEvent("VPN_HOST", addr, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_dronebl class
diff --git a/spiderfoot/modules/sfp_duckduckgo.py b/spiderfoot/modules/sfp_duckduckgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a6167de5060f9acc5f99c6e40e3c42f577c35f5
--- /dev/null
+++ b/spiderfoot/modules/sfp_duckduckgo.py
@@ -0,0 +1,137 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_duckduckgo
+# Purpose: Queries DuckDuckGo's API for information abotut the target.
+#
+# Author: Steve Micallef
+#
+# Created: 21/07/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_duckduckgo(SpiderFootPlugin):
+
+ meta = {
+ 'name': "DuckDuckGo",
+ 'summary': "Query DuckDuckGo's API for descriptive information about your target.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://duckduckgo.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://api.duckduckgo.com/api",
+ "https://help.duckduckgo.com/company/partnerships/",
+ "https://help.duckduckgo.com/duckduckgo-help-pages/"
+ ],
+ 'favIcon': "https://duckduckgo.com/favicon.ico",
+ 'logo': "https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png",
+ 'description': "Our Instant Answer API gives you free access to many of our instant answers like: "
+ "topic summaries , categories, disambiguation, and !bang redirects.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "affiliatedomains": True
+ }
+
+ # Option descriptions
+ optdescs = {
+ "affiliatedomains": "For affiliates, look up the domain name, not the hostname. This will usually return more meaningful information about the affiliate."
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "DOMAIN_NAME_PARENT",
+ "INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["DESCRIPTION_CATEGORY", "DESCRIPTION_ABSTRACT",
+ "AFFILIATE_DESCRIPTION_CATEGORY",
+ "AFFILIATE_DESCRIPTION_ABSTRACT"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.opts['affiliatedomains'] and "AFFILIATE_" in eventName:
+ eventData = self.sf.hostDomain(eventData, self.opts['_internettlds'])
+ if not eventData:
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ url = "https://api.duckduckgo.com/?q=" + eventData + "&format=json&pretty=1"
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot")
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ return
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from DuckDuckGo: {e}")
+ return
+
+ if not ret['Heading']:
+ self.debug(f"No DuckDuckGo information for {eventData}")
+ return
+
+ abstract_text = ret.get('AbstractText')
+ if abstract_text:
+ event_type = "DESCRIPTION_ABSTRACT"
+
+ if "AFFILIATE" in eventName:
+ event_type = "AFFILIATE_" + event_type
+
+ evt = SpiderFootEvent(event_type, str(abstract_text), self.__name__, event)
+ self.notifyListeners(evt)
+
+ related_topics = ret.get('RelatedTopics')
+ if related_topics:
+ event_type = "DESCRIPTION_CATEGORY"
+
+ if "AFFILIATE" in eventName:
+ event_type = "AFFILIATE_" + event_type
+
+ for topic in related_topics:
+ if not isinstance(topic, dict):
+ self.debug("No category text found from DuckDuckGo.")
+ continue
+
+ category = topic.get('Text')
+
+ if not category:
+ self.debug("No category text found from DuckDuckGo.")
+ continue
+
+ evt = SpiderFootEvent(event_type, category, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_duckduckgo class
diff --git a/spiderfoot/modules/sfp_email.py b/spiderfoot/modules/sfp_email.py
new file mode 100644
index 0000000000000000000000000000000000000000..c03689d477d964fb8d0caa7473e5a4f925184c88
--- /dev/null
+++ b/spiderfoot/modules/sfp_email.py
@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_email
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying e-mail addresses
+#
+# Author: Steve Micallef
+#
+# Created: 06/04/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_email(SpiderFootPlugin):
+
+ meta = {
+ 'name': "E-Mail Address Extractor",
+ 'summary': "Identify e-mail addresses in any obtained data.",
+ 'useCases': ["Passive", "Investigate", "Footprint"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT", "BASE64_DATA", "AFFILIATE_DOMAIN_WHOIS",
+ "CO_HOSTED_SITE_DOMAIN_WHOIS", "DOMAIN_WHOIS", "NETBLOCK_WHOIS",
+ "LEAKSITE_CONTENT", "RAW_DNS_RECORDS", "RAW_FILE_META_DATA",
+ 'RAW_RIR_DATA', "SIMILARDOMAIN_WHOIS",
+ "SSL_CERTIFICATE_RAW", "SSL_CERTIFICATE_ISSUED", "TCP_PORT_OPEN_BANNER",
+ "WEBSERVER_BANNER", "WEBSERVER_HTTPHEADERS"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["EMAILADDR", "EMAILADDR_GENERIC", "AFFILIATE_EMAILADDR"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ emails = SpiderFootHelpers.extractEmailsFromText(eventData)
+ for email in set(emails):
+ evttype = "EMAILADDR"
+ email = email.lower()
+
+ # Get the domain and strip potential ending .
+ mailDom = email.split('@')[1].strip('.')
+ if not self.sf.validHost(mailDom, self.opts['_internettlds']):
+ self.debug(f"Skipping {email} as not a valid e-mail.")
+ continue
+
+ if not self.getTarget().matches(mailDom, includeChildren=True, includeParents=True) and not self.getTarget().matches(email):
+ self.debug("External domain, so possible affiliate e-mail")
+ evttype = "AFFILIATE_EMAILADDR"
+
+ if eventName.startswith("AFFILIATE_"):
+ evttype = "AFFILIATE_EMAILADDR"
+
+ if not evttype.startswith("AFFILIATE_") and email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+
+ self.info(f"Found e-mail address: {email}")
+ mail = email.strip('.')
+
+ evt = SpiderFootEvent(evttype, mail, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+# End of sfp_email class
diff --git a/spiderfoot/modules/sfp_emailcrawlr.py b/spiderfoot/modules/sfp_emailcrawlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cd135a28ef7fa64a3634ea7fec829094ce98d57
--- /dev/null
+++ b/spiderfoot/modules/sfp_emailcrawlr.py
@@ -0,0 +1,221 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_emailcrawlr
+# Purpose: Search EmailCrawlr for email addresses and phone numbers
+# associated with a domain.
+#
+# Authors:
+#
+# Created: 2020-06-19
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_emailcrawlr(SpiderFootPlugin):
+
+ meta = {
+ 'name': "EmailCrawlr",
+ 'summary': "Search EmailCrawlr for email addresses and phone numbers associated with a domain.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://emailcrawlr.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://emailcrawlr.com/docs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://emailcrawlr.com",
+ "Sign up for free account",
+ "Navigate to https://emailcrawlr.com/dashboard",
+ "The API key is listed under 'API Key'"
+ ],
+ 'favIcon': "https://emailcrawlr.com/assets/fav-165eaa698b0dc774f0b250fadb2b41266e4c70dfbd7fb5fd4413e4bdecfd229d.png",
+ 'logo': "https://emailcrawlr.com/assets/logo_black-d136617b2fc5d52df6eea245a4db78477d8d99f873e08c24a9c3c7defe1c1379.png",
+ 'description': "By using the EmailCrawlr JSON API you can: "
+ "Get key information about company websites.\n"
+ "Find all email addresses associated with a domain.\n"
+ "Get social accounts associated with an email.\n"
+ "Verify email address deliverability.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "delay": 1,
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "EmailCrawlr API key.",
+ "delay": "Delay between requests, in seconds.",
+ }
+
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "EMAILADDR", "EMAILADDR_GENERIC",
+ "PHONE_NUMBER", "GEOINFO"]
+
+ # Query domain
+ # https://emailcrawlr.com/docs
+ def queryDomain(self, qry):
+ params = {
+ 'domain': qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ 'Accept': "application/json",
+ 'x-api-key': self.opts['api_key']
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.emailcrawlr.com/v2/domain?{urllib.parse.urlencode(params)}",
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from EmailCrawlr.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results for query")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid EmailCrawlr API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by EmailCrawlr")
+ self.errorState = True
+ return None
+
+ if res['code'] == '503':
+ self.error("EmailCrawlr service unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all other non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from EmailCrawlr")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_emailcrawlr but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName in ["DOMAIN_NAME"]:
+ data = self.queryDomain(eventData)
+
+ if data is None:
+ self.debug(f"No information found for domain {eventData}")
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ emails = data.get("emails")
+
+ if not emails:
+ self.info(f"No emails found for domain {eventData}")
+ return
+
+ for res in emails:
+ email = res.get('email')
+ if email:
+ mail_domain = email.lower().split('@')[1]
+ if self.getTarget().matches(mail_domain, includeChildren=True):
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+
+ name = res.get('name')
+ if name:
+ full_name = name.get('name')
+ if full_name and len(full_name) > 3:
+ evt = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {full_name}",
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+ phone_numbers = res.get('numbers')
+ if phone_numbers:
+ for number in phone_numbers:
+ if number:
+ evt = SpiderFootEvent("PHONE_NUMBER", number, self.__name__, event)
+ self.notifyListeners(evt)
+
+ location = res.get('location')
+ if location:
+ loc = ', '.join([_f for _f in [location.get('city'), location.get('country')] if _f])
+ if loc:
+ evt = SpiderFootEvent("GEOINFO", loc, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_emailcrawlr class
diff --git a/spiderfoot/modules/sfp_emailformat.py b/spiderfoot/modules/sfp_emailformat.py
new file mode 100644
index 0000000000000000000000000000000000000000..4207bd02187d7504f66c3af0ccf8cf21937acd1b
--- /dev/null
+++ b/spiderfoot/modules/sfp_emailformat.py
@@ -0,0 +1,115 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_emailformat
+# Purpose: SpiderFoot plug-in for retrieving e-mail addresses
+# belonging to your target from email-format.com.
+#
+# Author:
+#
+# Created: 29/09/2018
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from bs4 import BeautifulSoup
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_emailformat(SpiderFootPlugin):
+
+ meta = {
+ 'name': "EmailFormat",
+ 'summary': "Look up e-mail addresses on email-format.com.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://www.email-format.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.email-format.com/i/api_access/",
+ "https://www.email-format.com/i/api_v2/",
+ "https://www.email-format.com/i/api_v1/"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://www.email-format.com/",
+ 'logo': "https://www.google.com/s2/favicons?domain=https://www.email-format.com/",
+ 'description': "Save time and energy - find the email address formats in use at thousands of companies.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['INTERNET_NAME', "DOMAIN_NAME"]
+
+ def producedEvents(self):
+ return ["EMAILADDR", "EMAILADDR_GENERIC"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Get e-mail addresses on this domain
+ res = self.sf.fetchUrl(f"https://www.email-format.com/d/{eventData}/", timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ return
+
+ html = BeautifulSoup(res["content"], features="lxml")
+ if not html:
+ return
+
+ tbody = html.find('tbody')
+ if tbody:
+ data = str(tbody.contents)
+ else:
+ # fall back to raw page contents
+ data = res["content"]
+
+ emails = SpiderFootHelpers.extractEmailsFromText(data)
+ for email in emails:
+ # Skip unrelated emails
+ mailDom = email.lower().split('@')[1]
+ if not self.getTarget().matches(mailDom):
+ self.debug(f"Skipped address: {email}")
+ continue
+
+ # Skip masked emails
+ if re.match(r"^[0-9a-f]{8}\.[0-9]{7}@", email):
+ self.debug(f"Skipped address: {email}")
+ continue
+
+ self.info(f"Found e-mail address: {email}")
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_emailformat class
diff --git a/spiderfoot/modules/sfp_emailrep.py b/spiderfoot/modules/sfp_emailrep.py
new file mode 100644
index 0000000000000000000000000000000000000000..80811e099bb48bf13b658d5d8f35ceaa37d45482
--- /dev/null
+++ b/spiderfoot/modules/sfp_emailrep.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_emailrep
+# Purpose: Searches EmailRep.io for email address reputation.
+#
+# Author:
+#
+# Created: 2019-08-07
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_emailrep(SpiderFootPlugin):
+
+ meta = {
+ 'name': "EmailRep",
+ 'summary': "Search EmailRep.io for email address reputation.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://emailrep.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.emailrep.io/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://emailrep.io/free",
+ "Request a free API Key",
+ "The API key will be sent to registered email account on approval"
+ ],
+ 'favIcon': "https://emailrep.io/assets/img/favicon.png",
+ 'logo': "https://emailrep.io/assets/img/logo-light.png",
+ 'description': "Illuminate the \"reputation\" behind an email address.\n"
+ "EmailRep uses hundreds of factors like domain age, traffic rankings, "
+ "presence on social media sites, professional networking sites, personal connections, "
+ "public records, deliverability, data breaches, dark web credential leaks, "
+ "phishing emails, threat actor emails, and more to answer these types of questions.",
+ }
+ }
+
+ opts = {
+ 'api_key': '',
+ }
+
+ optdescs = {
+ 'api_key': 'EmailRep API key.',
+ }
+
+ results = None
+ errorState = False
+ errorWarned = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['EMAILADDR']
+
+ def producedEvents(self):
+ return ['RAW_RIR_DATA', 'EMAILADDR_COMPROMISED', 'MALICIOUS_EMAILADDR']
+
+ # https://emailrep.io/docs/
+ def query(self, qry):
+ headers = {
+ 'Accept': "application/json"
+ }
+
+ if self.opts['api_key'] != '':
+ headers['Key'] = self.opts['api_key']
+
+ res = self.sf.fetchUrl(
+ 'https://emailrep.io/' + qry,
+ headers=headers,
+ useragent='SpiderFoot',
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ # Documentation does not indicate rate limit threshold (50 queries/day)
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ if res['code'] == '400':
+ self.error('API error: Bad request')
+ self.errorState = True
+ return None
+
+ if res['code'] == '401':
+ self.error('API error: Invalid API key')
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error('API error: Too Many Requests')
+ self.errorState = True
+ return None
+
+ if res['code'] != '200':
+ self.error('Unexpected reply from EmailRep.io: ' + res['code'])
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == '' and not self.errorWarned:
+ self.error("Warning: You enabled sfp_emailrep but did not set an API key! Queries will be rate limited.")
+ self.errorWarned = True
+
+ res = self.query(eventData)
+
+ if res is None:
+ return
+
+ details = res.get('details')
+
+ if not details:
+ return
+
+ credentials_leaked = details.get('credentials_leaked')
+ if credentials_leaked:
+ evt = SpiderFootEvent('EMAILADDR_COMPROMISED', eventData + " [Unknown]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ malicious_activity = details.get('malicious_activity')
+ if malicious_activity:
+ evt = SpiderFootEvent('MALICIOUS_EMAILADDR', 'EmailRep [' + eventData + ']', self.__name__, event)
+ self.notifyListeners(evt)
+
+ if malicious_activity or credentials_leaked:
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(res), self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_emailrep class
diff --git a/spiderfoot/modules/sfp_emergingthreats.py b/spiderfoot/modules/sfp_emergingthreats.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a270eecc17947440eeb86e1fca4155aa4a229e9
--- /dev/null
+++ b/spiderfoot/modules/sfp_emergingthreats.py
@@ -0,0 +1,186 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_emergingthreats
+# Purpose: Checks if an IP address or netblock is malicious according to
+# EmergingThreats.net.
+#
+# Author: steve@binarypool.com
+#
+# Created: 16/05/2020
+# Copyright: (c) Steve Micallef, 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_emergingthreats(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Emerging Threats",
+ 'summary': "Check if a netblock or IP address is malicious according to EmergingThreats.net.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://rules.emergingthreats.net/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://doc.emergingthreats.net/"
+ ],
+ 'favIcon': "https://doc.emergingthreats.net/pub/Main/WebPreferences/favicon.ico",
+ 'logo': "https://doc.emergingthreats.net/logo.png",
+ 'description': "Emerging Threats delivers the most timely and accurate threat intelligence.\n"
+ "Emerging Threat (ET) intelligence helps prevent attacks and reduce risk by "
+ "helping you understand the historical context of where these threats originated, "
+ "who is behind them, when have they attacked, what methods they used, and what they're after. "
+ "Get on-demand access to current and historical metadata on IPs, domains, "
+ "and other related threat intelligence to help research threats and investigate incidents.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliate IP addresses?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "NETBLOCK_MEMBER",
+ "NETBLOCK_OWNER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_NETBLOCK",
+ ]
+
+ def query(self, qry, targetType):
+ cid = "_emergingthreats"
+ url = "https://rules.emergingthreats.net/blockrules/compromised-ips.txt"
+
+ data = dict()
+ data["content"] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))
+
+ if data["content"] is None:
+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if data["code"] != "200":
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ if data["content"] is None:
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("sfmal_" + cid, data['content'])
+
+ for line in data["content"].split('\n'):
+ ip = line.strip().lower()
+
+ if targetType == "netblock":
+ try:
+ if IPAddress(ip) in IPNetwork(qry):
+ self.debug(f"{ip} found within netblock/subnet {qry} in EmergingThreats.net list.")
+ return url
+ except Exception as e:
+ self.debug(f"Error encountered parsing: {e}")
+ continue
+
+ if targetType == "ip":
+ if qry.lower() == ip:
+ self.debug(f"{qry} found in EmergingThreats.net list.")
+ return url
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} with EmergingThreats.net")
+
+ url = self.query(eventData, targetType)
+
+ if not url:
+ return
+
+ text = f"EmergingThreats.net [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_emergingthreats class
diff --git a/spiderfoot/modules/sfp_errors.py b/spiderfoot/modules/sfp_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b83057060426fbb54cf68175dd13cf26c3ea074
--- /dev/null
+++ b/spiderfoot/modules/sfp_errors.py
@@ -0,0 +1,108 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_errors
+# Purpose: Identify common error messages in content like SQL errors, etc.
+#
+# Author: Steve Micallef
+#
+# Created: 18/01/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+# Taken from Google Dorks on exploit-db.com
+regexps = dict({
+ "PHP Error": ["PHP pase error", "PHP warning", "PHP error",
+ "unexpected T_VARIABLE", "warning: failed opening", "include_path="],
+ "Generic Error": ["Internal Server Error", "Incorrect syntax"],
+ "Oracle Error": [r"ORA-\d+", "TNS:.?no listen"],
+ "ASP Error": ["NET_SessionId"],
+ "MySQL Error": [r"mysql_query\(", r"mysql_connect\("],
+ "ODBC Error": [r"\[ODBC SQL"]
+
+})
+
+
+class sfp_errors(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Error String Extractor",
+ 'summary': "Identify common error messages in content like SQL errors, etc.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {}
+
+ # Option descriptions
+ optdescs = {
+ # For each option in opts you should have a key/value pair here
+ # describing it. It will end up in the UI to explain the option
+ # to the end-user.
+ }
+
+ # Target
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ # * = be notified about all events.
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["ERROR_MESSAGE"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ # We only want web content from the target
+ if srcModuleName != "sfp_spider":
+ return
+
+ eventSource = event.actualSource
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventSource not in list(self.results.keys()):
+ self.results[eventSource] = list()
+
+ # We only want web content for pages on the target site
+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):
+ self.debug("Not collecting web content information for external sites.")
+ return
+
+ for regexpGrp in list(regexps.keys()):
+ if regexpGrp in self.results[eventSource]:
+ continue
+
+ for regex in regexps[regexpGrp]:
+ pat = re.compile(regex, re.IGNORECASE)
+ matches = re.findall(pat, eventData)
+ if len(matches) > 0 and regexpGrp not in self.results[eventSource]:
+ self.info("Matched " + regexpGrp + " in content from " + eventSource)
+ self.results[eventSource] = self.results[eventSource] + [regexpGrp]
+ evt = SpiderFootEvent("ERROR_MESSAGE", regexpGrp,
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_errors class
diff --git a/spiderfoot/modules/sfp_ethereum.py b/spiderfoot/modules/sfp_ethereum.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a6b2250bb2155bc50bc5001384de3f7c8640ba2
--- /dev/null
+++ b/spiderfoot/modules/sfp_ethereum.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ethereum
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying ethereum addresses.
+#
+# Author: Steve Micallef
+#
+# Created: 03/09/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ethereum(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Ethereum Address Extractor",
+ 'summary': "Identify ethereum addresses in scraped webpages.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {}
+ optdescs = {}
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["ETHEREUM_ADDRESS"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ sourceData = self.sf.hashstring(eventData)
+
+ if sourceData in self.results:
+ return
+
+ self.results[sourceData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # thanks to https://stackoverflow.com/questions/21683680/regex-to-match-ethereum-addresses
+ matches = re.findall(r"[\s:=\>](0x[a-fA-F0-9]{40})", eventData)
+ for m in matches:
+ self.debug("Ethereum address match: " + m)
+ evt = SpiderFootEvent("ETHEREUM_ADDRESS", m, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_ethereum class
diff --git a/spiderfoot/modules/sfp_etherscan.py b/spiderfoot/modules/sfp_etherscan.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ff2df2d1c5b78fd83e69c157df80f4f2263b934
--- /dev/null
+++ b/spiderfoot/modules/sfp_etherscan.py
@@ -0,0 +1,140 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_etherscan
+# Purpose: SpiderFoot plug-in to look up a ethereum wallet's balance by
+# querying etherscan.io.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 26/01/2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_etherscan(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Etherscan",
+ 'summary': "Queries etherscan.io to find the balance of identified ethereum wallet addresses.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Public Registries"],
+ 'dataSource': {
+ 'website': "https://etherscan.io",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://etherscan.io/apis"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://etherscan.io",
+ "Register a free account",
+ "Browse to https://etherscan.io/myapikey",
+ "Click on Add beside API Key",
+ "Your API Key will be listed under API Key Token",
+ ],
+ 'favIcon': "https://etherscan.io/images/favicon3.ico",
+ 'logo': "https://etherscan.io/images/brandassets/etherscan-logo-circle.png",
+ 'description': "Etherscan allows you to explore and search the Ethereum blockchain "
+ "for transactions, addresses, tokens, prices and other activities taking place on Ethereum (ETH)",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': '',
+ 'pause': 1
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': "API Key for etherscan.io",
+ 'pause': "Number of seconds to wait between each API call."
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "ETHEREUM_ADDRESS"
+ ]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return [
+ "ETHEREUM_BALANCE",
+ "RAW_RIR_DATA"
+ ]
+
+ def query(self, qry):
+ queryString = f"https://api.etherscan.io/api?module=account&action=balance&address={qry}&tag=latest&apikey={self.opts['api_key']}"
+ # Wallet balance
+ res = self.sf.fetchUrl(queryString,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['pause'])
+
+ if res['content'] is None:
+ self.info(f"No Etherscan data found for {qry}")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_etherscan but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+ if data is None:
+ self.info(f"No Etherscan data found for {eventData}")
+ return
+
+ # Value returned by etherscan was too large in comparison to actual wallet balance
+ balance = float(data.get('result')) / 1000000000000000000
+
+ evt = SpiderFootEvent("ETHEREUM_BALANCE", f"{str(balance)} ETH", self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_etherscan class
diff --git a/spiderfoot/modules/sfp_filemeta.py b/spiderfoot/modules/sfp_filemeta.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad26b50b30a2be88cfaddf6697583cf05704578
--- /dev/null
+++ b/spiderfoot/modules/sfp_filemeta.py
@@ -0,0 +1,184 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_filemeta
+# Purpose: From Spidering and from searching search engines, extracts file
+# meta data from files matching certain file extensions.
+#
+# Author: Steve Micallef
+#
+# Created: 25/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import io
+import mimetypes
+
+import PyPDF2
+
+import docx
+
+import exifread
+
+import pptx
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_filemeta(SpiderFootPlugin):
+
+ meta = {
+ 'name': "File Metadata Extractor",
+ 'summary': "Extracts meta data from documents and images.",
+ 'flags': [],
+ 'useCases': ["Footprint"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ 'fileexts': ["docx", "pptx", 'pdf', 'jpg', 'jpeg', 'tiff', 'tif'],
+ 'timeout': 300
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'fileexts': "File extensions of files you want to analyze the meta data of (only PDF, DOCX, XLSX and PPTX are supported.)",
+ 'timeout': "Download timeout for files, in seconds."
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL", "INTERESTING_FILE"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["RAW_FILE_META_DATA", "SOFTWARE_USED"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ for fileExt in self.opts['fileexts']:
+ if self.checkForStop():
+ return
+
+ if "." + fileExt.lower() in eventData.lower():
+ # Fetch the file, allow much more time given that these files are
+ # typically large.
+ ret = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent'], disableContentEncoding=True,
+ sizeLimit=10000000,
+ verify=False)
+ if ret['content'] is None:
+ self.error(f"Unable to fetch file for meta analysis: {eventData}")
+ return
+
+ if len(ret['content']) < 512:
+ self.error(f"Strange content encountered, size of {len(ret['content'])}")
+ return
+
+ meta = None
+ data = None
+ # Based on the file extension, handle it
+ if fileExt.lower() == "pdf":
+ try:
+ raw = io.BytesIO(ret['content'])
+ # data = metapdf.MetaPdfReader().read_metadata(raw)
+ pdf = PyPDF2.PdfFileReader(raw, strict=False)
+ data = pdf.getDocumentInfo()
+ meta = str(data)
+ self.debug("Obtained meta data from " + eventData)
+ except Exception as e:
+ self.error(f"Unable to parse meta data from: {eventData} ({e})")
+ return
+
+ if fileExt.lower() in ["docx"]:
+ try:
+ c = io.BytesIO(ret['content'])
+ doc = docx.Document(c)
+ mtype = mimetypes.guess_type(eventData)[0]
+ self.debug("Office type: " + str(mtype))
+ a = doc.core_properties.author
+ c = doc.core_properties.comments
+ data = [_f for _f in [a, c] if _f]
+ meta = ", ".join(data)
+ except Exception as e:
+ self.error(f"Unable to process file: {eventData} ({e})")
+ return
+
+ if fileExt.lower() in ["pptx"]:
+ try:
+ c = io.BytesIO(ret['content'])
+ doc = pptx.Presentation(c)
+ mtype = mimetypes.guess_type(eventData)[0]
+ self.debug("Office type: " + str(mtype))
+ a = doc.core_properties.author
+ c = doc.core_properties.comments
+ data = [_f for _f in [a, c] if _f]
+ meta = ", ".join(data)
+ except Exception as e:
+ self.error(f"Unable to process file: {eventData} ({e})")
+ return
+
+ if fileExt.lower() in ["jpg", "jpeg", "tiff"]:
+ try:
+ raw = io.BytesIO(ret['content'])
+ data = exifread.process_file(raw)
+ if data is None or len(data) == 0:
+ continue
+ meta = str(data)
+ except Exception as e:
+ self.error(f"Unable to parse meta data from: {eventData} ({e})")
+ return
+
+ if meta is not None and data is not None:
+ rawevt = SpiderFootEvent("RAW_FILE_META_DATA", meta,
+ self.__name__, event)
+ self.notifyListeners(rawevt)
+
+ val = list()
+ try:
+ if "/Producer" in data:
+ val.append(str(data['/Producer']))
+
+ if "/Creator" in data:
+ val.append(str(data['/Creator']))
+
+ if "Application" in data:
+ val.append(str(data['Application']))
+
+ if "Image Software" in data:
+ val.append(str(data['Image Software']))
+ except Exception as e:
+ self.error("Failed to parse PDF, " + eventData + ": " + str(e))
+ return
+
+ for v in val:
+ if v and not isinstance(v, PyPDF2.generic.NullObject):
+ self.debug("VAL: " + str(val))
+ # Strip non-ASCII
+ v = ''.join([i if ord(i) < 128 else ' ' for i in v])
+ evt = SpiderFootEvent("SOFTWARE_USED", v, self.__name__, rawevt)
+ self.notifyListeners(evt)
diff --git a/spiderfoot/modules/sfp_flickr.py b/spiderfoot/modules/sfp_flickr.py
new file mode 100644
index 0000000000000000000000000000000000000000..afc2413c266fdec5417e4f00cc72c322154e8dff
--- /dev/null
+++ b/spiderfoot/modules/sfp_flickr.py
@@ -0,0 +1,266 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_flickr
+# Purpose: Search Flickr API for domains, URLs and emails related to the
+# specified domain.
+#
+# Author:
+#
+# Created: 2018-10-08
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_flickr(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Flickr",
+ 'summary': "Search Flickr for domains, URLs and emails related to the specified domain.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Social Media"],
+ 'dataSource': {
+ 'website': "https://www.flickr.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.flickr.com/services/api/",
+ "https://www.flickr.com/services/developer/api/",
+ "https://code.flickr.net/"
+ ],
+ 'favIcon': "https://combo.staticflickr.com/pw/favicon.ico",
+ 'logo': "https://combo.staticflickr.com/pw/favicon.ico",
+ 'description': "Flickr is almost certainly the best online photo management and sharing application in the world.\n "
+ "On Flickr, members upload photos, share them securely, supplement their photos with "
+ "metadata like license information, geo-location, people, tags, etc., "
+ "and interact with their family, friends, contacts or anyone in the community. "
+ "Practically all the features on Flickr's various platforms -- web, mobile and desktop -- "
+ "are accompanied by a longstanding API program. "
+ "Since 2005, developers have collaborated on top of Flickr's APIs to build fun, creative, "
+ "and gorgeous experiences around photos that extend beyond Flickr.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'pause': 1,
+ 'per_page': 100,
+ 'maxpages': 20,
+ 'dns_resolve': True,
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'pause': "Number of seconds to pause between fetches.",
+ 'per_page': "Maximum number of results per page.",
+ 'maxpages': "Maximum number of pages of results to fetch.",
+ 'dns_resolve': "DNS resolve each identified domain.",
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["EMAILADDR", "EMAILADDR_GENERIC", "INTERNET_NAME",
+ "DOMAIN_NAME", "LINKED_URL_INTERNAL"]
+
+ # Retrieve API key
+ def retrieveApiKey(self):
+ res = self.sf.fetchUrl("https://www.flickr.com/", timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ return None
+
+ keys = re.findall(r'YUI_config.flickr.api.site_key = "([a-zA-Z0-9]+)"', str(res['content']))
+
+ if not keys:
+ return None
+
+ return keys[0]
+
+ # Query the REST API
+ def query(self, qry, api_key, page=1, per_page=200):
+ params = {
+ "sort": "relevance",
+ "parse_tags": "1",
+ "content_type": "7",
+ "extras": "description,owner_name,path_alias,realname",
+ "hermes": "1",
+ "hermesClient": "1",
+ "reqId": "",
+ "nojsoncallback": "1",
+ "viewerNSID": "",
+ "method": "flickr.photos.search",
+ "csrf": "",
+ "lang": "en-US",
+ "per_page": str(per_page),
+ "page": str(page),
+ "text": qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ "api_key": api_key,
+ "format": "json"
+ }
+
+ res = self.sf.fetchUrl("https://api.flickr.com/services/rest?" + urllib.parse.urlencode(params),
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(self.opts['pause'])
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked")
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == 'sfp_flickr':
+ self.debug(f"Ignoring {eventData}, from self.")
+ return
+
+ # Retrieve API key
+ api_key = self.retrieveApiKey()
+
+ if not api_key:
+ self.error("Failed to obtain API key")
+ return
+
+ self.debug(f"Retrieved API key: {api_key}")
+
+ # Query API for event data
+ hosts = list()
+ page = 1
+ pages = self.opts['maxpages']
+ per_page = self.opts['per_page']
+ while page <= pages:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ data = self.query(eventData, api_key, page=page, per_page=per_page)
+
+ if data is None:
+ return
+
+ # Check the response is ok
+ if data.get('stat') != "ok":
+ self.debug("Error retrieving search results.")
+ return
+
+ photos = data.get('photos')
+
+ if not photos:
+ self.debug("No search results.")
+ return
+
+ # Calculate number of pages to retrieve
+ result_pages = int(photos.get('pages', 0))
+
+ if result_pages < pages:
+ pages = result_pages
+
+ if 'max_allowed_pages' in photos:
+ allowed_pages = int(photos.get('max_allowed_pages', 0))
+ if pages > allowed_pages:
+ pages = allowed_pages
+
+ self.info(f"Parsing page {page} of {pages}")
+
+ # Extract data
+ for photo in photos.get('photo', list()):
+ emails = SpiderFootHelpers.extractEmailsFromText(str(photo))
+ for email in emails:
+ if email in self.results:
+ continue
+
+ mail_domain = email.lower().split('@')[1]
+
+ if not self.getTarget().matches(mail_domain, includeChildren=True, includeParents=True):
+ self.debug(f"Skipped unrelated address: {email}")
+ continue
+
+ self.info("Found e-mail address: " + email)
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+ self.results[email] = True
+
+ links = SpiderFootHelpers.extractUrlsFromText(str(photo))
+ for link in links:
+ if link in self.results:
+ continue
+
+ host = self.sf.urlFQDN(link)
+
+ if not self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ self.debug(f"Skipped unrelated URL: {link}")
+ continue
+
+ hosts.append(host)
+
+ self.debug(f"Found a URL: {link}")
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', link, self.__name__, event)
+ self.notifyListeners(evt)
+ self.results[link] = True
+
+ page += 1
+
+ for host in set(hosts):
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ if self.opts['dns_resolve'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ evt = SpiderFootEvent("INTERNET_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+ if self.sf.isDomain(host, self.opts["_internettlds"]):
+ evt = SpiderFootEvent("DOMAIN_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_flickr class
diff --git a/spiderfoot/modules/sfp_focsec.py b/spiderfoot/modules/sfp_focsec.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f3121a7b1151ce5f5c5334951debbc6fd8e5e96
--- /dev/null
+++ b/spiderfoot/modules/sfp_focsec.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_focsec
+# Purpose: Look up IP address information from Focsec.
+#
+# Author:
+#
+# Created: 2021-10-09
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_focsec(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Focsec",
+ 'summary': "Look up IP address information from Focsec.",
+ 'flags': ['apikey'],
+ 'useCases': ["Passive", "Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://focsec.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.focsec.com/#ip",
+ ],
+ "apiKeyInstructions": [
+ "Visit https://focsec.com/signup",
+ "Register an account",
+ "Visit https://focsec.com/account/dashboard and use the API key provided",
+ ],
+ 'favIcon': "https://focsec.com/static/favicon.png",
+ 'logo': "https://focsec.com/static/web/images/logo.png",
+ 'description': "Our API lets you know if a user's IP address is associated with a VPN, Proxy, TOR or malicious bots."
+ "Take your applications security to the next level by detecting suspicious activity early on."
+ }
+ }
+
+ opts = {
+ "api_key": "",
+ }
+
+ optdescs = {
+ "api_key": "Focsec API Key.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS"
+ ]
+
+ def producedEvents(self):
+ return [
+ "RAW_RIR_DATA",
+ "GEOINFO",
+ "MALICIOUS_IPADDR",
+ "PROXY_HOST",
+ "VPN_HOST",
+ "TOR_EXIT_NODE",
+ ]
+
+ def query(self, qry):
+ """Retrieve IP address information from Focsec.
+
+ Args:
+ qry (str): IPv4/IPv6 address
+
+ Returns:
+ dict: JSON formatted results
+ """
+
+ params = urllib.parse.urlencode({
+ 'api_key': self.opts["api_key"],
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.focsec.com/v1/ip/{qry}?{params}",
+ timeout=self.opts["_fetchtimeout"],
+ useragent=self.opts['_useragent']
+ )
+
+ if not res:
+ self.error("No response from Focsec.")
+ return None
+
+ if res['code'] == "400":
+ self.error("Bad request.")
+ self.errorState = True
+ return None
+
+ if res['code'] == "401":
+ self.error("Unauthorized - Invalid API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == "402":
+ self.error("Unauthorized - Payment Required. Subscription or trial period expired.")
+ self.errorState = True
+ return None
+
+ if res['code'] == "404":
+ self.debug(f"No results for {qry}")
+ return None
+
+ # Future proofing - Focsec does not implement rate limiting
+ if res['code'] == "429":
+ self.error("You are being rate-limited by Focsec.")
+ return None
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from Focsec.")
+ return None
+
+ if not res['content']:
+ self.debug("No results from Focsec.")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ data = self.query(eventData)
+
+ if not data:
+ self.debug(f"Found no results for {eventData}")
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ is_bot = data.get('is_bot')
+ if is_bot:
+ e = SpiderFootEvent("MALICIOUS_IPADDR", f"Focsec [{eventData}]", self.__name__, event)
+ self.notifyListeners(e)
+
+ is_tor = data.get('is_tor')
+ if is_tor:
+ e = SpiderFootEvent("TOR_EXIT_NODE", eventData, self.__name__, event)
+ self.notifyListeners(e)
+
+ is_vpn = data.get('is_vpn')
+ if is_vpn:
+ e = SpiderFootEvent("VPN_HOST", eventData, self.__name__, event)
+ self.notifyListeners(e)
+
+ is_proxy = data.get('is_proxy')
+ if is_proxy:
+ e = SpiderFootEvent("PROXY_HOST", eventData, self.__name__, event)
+ self.notifyListeners(e)
+
+ location = ', '.join(
+ filter(
+ None,
+ [
+ data.get('city'),
+ data.get('country'),
+ ]
+ )
+ )
+
+ if location:
+ e = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_focsec class
diff --git a/spiderfoot/modules/sfp_fortinet.py b/spiderfoot/modules/sfp_fortinet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e25c78d3d410eb6124613025ac457c395f481cdc
--- /dev/null
+++ b/spiderfoot/modules/sfp_fortinet.py
@@ -0,0 +1,137 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_fortinet
+# Purpose: Check if an IP address is malicious according to FortiGuard Antispam.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_fortinet(SpiderFootPlugin):
+
+ meta = {
+ 'name': "FortiGuard Antispam",
+ 'summary': "Check if an IP address is malicious according to FortiGuard Antispam.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.fortiguard.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.fortiguard.com/learnmore#as",
+ ],
+ 'favIcon': "https://www.fortiguard.com/static/images/favicon.ico",
+ 'logo': "https://www.fortiguard.com/static/images/Fortinet-logo%20white.png?v=880",
+ 'description': "FortiGuard Antispam provides a comprehensive and multi-layered approach to detect and filter spam processed by organizations."
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ ]
+
+ def query(self, ip):
+ if not ip:
+ return None
+
+ res = self.sf.fetchUrl(
+ f"https://www.fortiguard.com/search?q={ip}&engine=8",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from FortiGuard Antispam.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from FortiGuard Antispam")
+ self.errorState = True
+ return None
+
+ return res['content']
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ malicious_type = 'MALICIOUS_IPADDR'
+ blacklist_type = 'BLACKLISTED_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = 'MALICIOUS_AFFILIATE_IPADDR'
+ blacklist_type = 'BLACKLISTED_AFFILIATE_IPADDR'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ data = self.query(eventData)
+
+ if not data:
+ return
+
+ if "Your signature is on the blocklist" not in data:
+ return
+
+ url = f"https://www.fortiguard.com/search?q={eventData}&engine=8"
+ text = f"FortiGuard Antispam [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_fortinet class
diff --git a/spiderfoot/modules/sfp_fraudguard.py b/spiderfoot/modules/sfp_fraudguard.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a3bbc7501112edc75343fb6ba7c64e05d89ea36
--- /dev/null
+++ b/spiderfoot/modules/sfp_fraudguard.py
@@ -0,0 +1,279 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_fraudguard
+# Purpose: Query fraudguard.io using their API
+#
+# Author: Steve Micallef
+#
+# Created: 18/06/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import base64
+import json
+import time
+from datetime import datetime
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_fraudguard(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Fraudguard",
+ 'summary': "Obtain threat information from Fraudguard.io",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://fraudguard.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://docs.fraudguard.io/",
+ "https://faq.fraudguard.io/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://app.fraudguard.io/register",
+ "Register a free account",
+ "Navigate to https://app.fraudguard.io/keys",
+ "The API key combination is listed under Username and Password"
+ ],
+ 'favIcon': "https://fraudguard.io/img/favicon.ico",
+ 'logo': "https://s3.amazonaws.com/fraudguard.io/img/header.png",
+ 'description': "FraudGuard is a service designed to provide an easy way to validate usage "
+ "by continuously collecting and analyzing real-time internet traffic. "
+ "Utilizing just a few simple API endpoints we make integration as simple as possible "
+ "and return data such as: Risk Level, Threat Type, Geo Location, etc. Super fast, super simple.\n"
+ "Lookup any IP address by querying our threat engine.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "fraudguard_api_key_account": "",
+ "fraudguard_api_key_password": "",
+ "age_limit_days": 90,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxv6netblock': 120,
+ 'subnetlookup': True,
+ 'maxsubnet': 24,
+ 'maxv6subnet': 120,
+ 'checkaffiliates': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ "fraudguard_api_key_account": "Fraudguard.io API username.",
+ "fraudguard_api_key_password": "Fraudguard.io API password.",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum IPv4 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6netblock': "If looking up owned netblocks, the maximum IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",
+ 'maxsubnet': "If looking up subnets, the maximum IPv4 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxv6subnet': "If looking up subnets, the maximum IPv6 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'checkaffiliates': "Apply checks to affiliates?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ "NETBLOCK_MEMBER",
+ "NETBLOCKV6_MEMBER",
+ "NETBLOCK_OWNER",
+ "NETBLOCKV6_OWNER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "GEOINFO",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_NETBLOCK"
+ ]
+
+ def query(self, qry):
+ """Query IP address
+
+ Args:
+ qry (str): IPv4/IPv6 address
+
+ Returns:
+ dict: JSON formatted results
+ """
+
+ fraudguard_url = "https://api.fraudguard.io/ip/" + qry
+ api_key_account = self.opts['fraudguard_api_key_account']
+ if type(api_key_account) == str:
+ api_key_account = api_key_account.encode('utf-8')
+ api_key_password = self.opts['fraudguard_api_key_password']
+ if type(api_key_password) == str:
+ api_key_password = api_key_password.encode('utf-8')
+ token = base64.b64encode(api_key_account + ':'.encode('utf-8') + api_key_password)
+ headers = {
+ 'Authorization': "Basic " + token.decode('utf-8')
+ }
+
+ res = self.sf.fetchUrl(
+ fraudguard_url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ if res['code'] in ["400", "429", "500", "403"]:
+ self.error("Fraudguard.io API key seems to have been rejected or you have exceeded usage limits for the month.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.info(f"No Fraudguard.io info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from Fraudguard.io: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['fraudguard_api_key_account'] == "" or self.opts['fraudguard_api_key_password'] == "":
+ self.error("You enabled sfp_fraudguard but did not set an API username/password!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:
+ return
+
+ if eventName in ['NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ if not self.opts['netblocklookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_OWNER':
+ max_netblock = self.opts['maxv6netblock']
+ else:
+ max_netblock = self.opts['maxnetblock']
+
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ if eventName in ['NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ if not self.opts['subnetlookup']:
+ return
+
+ if eventName == 'NETBLOCKV6_MEMBER':
+ max_subnet = self.opts['maxv6subnet']
+ else:
+ max_subnet = self.opts['maxsubnet']
+
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS', 'NETBLOCK_OWNER', 'NETBLOCKV6_OWNER']:
+ evtType = 'MALICIOUS_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS', 'NETBLOCK_MEMBER', 'NETBLOCKV6_MEMBER']:
+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+ self.results[eventData] = True
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return
+
+ data = self.query(addr)
+
+ if not data:
+ continue
+
+ self.debug(f"Found results for {addr} in Fraudguard.io")
+
+ # Format: 2016-12-24T07:25:35+00:00'
+ created_dt = datetime.strptime(data.get('discover_date'), '%Y-%m-%d %H:%M:%S')
+ created_ts = int(time.mktime(created_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])
+ if self.opts['age_limit_days'] > 0 and created_ts < age_limit_ts:
+ self.debug(f"Record found but too old ({created_dt}), skipping.")
+ continue
+
+ # For netblocks, we need to create the IP address event so that
+ # the threat intel event is more meaningful.
+ if eventName == 'NETBLOCK_OWNER':
+ pevent = SpiderFootEvent("IP_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCKV6_OWNER':
+ pevent = SpiderFootEvent("IPV6_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCK_MEMBER':
+ pevent = SpiderFootEvent("AFFILIATE_IPADDR", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ elif eventName == 'NETBLOCKV6_MEMBER':
+ pevent = SpiderFootEvent("AFFILIATE_IPV6_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(pevent)
+ else:
+ pevent = event
+
+ geoinfo = [
+ _f for _f in [
+ data.get('state'),
+ data.get('city'),
+ data.get('postal_code'),
+ data.get('country')
+ ] if _f and _f != "unknown"
+ ]
+ if geoinfo:
+ location = ', '.join(filter(None, geoinfo))
+ e = SpiderFootEvent("GEOINFO", location, self.__name__, pevent)
+ self.notifyListeners(e)
+
+ threat = data.get('threat')
+ if threat and threat != "unknown":
+ risk_level = data.get('risk_level')
+ e = SpiderFootEvent(evtType, f"{threat} (risk level: {risk_level}) [{addr}]", self.__name__, pevent)
+ self.notifyListeners(e)
+
+# End of sfp_fraudguard class
diff --git a/spiderfoot/modules/sfp_fsecure_riddler.py b/spiderfoot/modules/sfp_fsecure_riddler.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e9f688be988dfb792eef16dca57417eb7b5135a
--- /dev/null
+++ b/spiderfoot/modules/sfp_fsecure_riddler.py
@@ -0,0 +1,265 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_fsecure_riddler
+# Purpose: Query F-Secure Riddler.io API.
+#
+# Author:
+#
+# Created: 2019-09-16
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_fsecure_riddler(SpiderFootPlugin):
+
+ meta = {
+ 'name': "F-Secure Riddler.io",
+ 'summary': "Obtain network information from F-Secure Riddler.io API.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://riddler.io/",
+ 'model': "PRIVATE_ONLY",
+ 'references': [
+ "https://riddler.io/help/api",
+ "https://riddler.io/help/search",
+ "https://riddler.io/static/riddler_white_paper.pdf",
+ "https://www.f-secure.com/en/business/products/vulnerability-management/radar"
+ ],
+ 'apiKeyInstructions': [
+ "Registration is disabled for new accounts"
+ ],
+ 'favIcon': "https://riddler.io/static/images/favicon.png",
+ 'logo': "https://riddler.io/static/images/logo.png",
+ 'description': "Riddler.io allows you to search in a high quality dataset with more than 396,831,739 hostnames. "
+ "Unlike others, we do not rely on simple port scanning techniques - we crawl the web, "
+ "ensuring an in-depth quality data set you will not find anywhere else.\n"
+ "Use Riddler to enumerate possible attack vectors during your pen-test or use the very same data "
+ "to monitor potential threats before it is too late.",
+ }
+ }
+
+ opts = {
+ 'verify': True,
+ 'username': '',
+ 'password': ''
+ }
+
+ optdescs = {
+ 'verify': 'Verify host names resolve',
+ 'username': 'F-Secure Riddler.io username',
+ 'password': 'F-Secure Riddler.io password'
+ }
+
+ results = None
+ token = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['DOMAIN_NAME', 'INTERNET_NAME',
+ 'INTERNET_NAME_UNRESOLVED', 'IP_ADDRESS']
+
+ def producedEvents(self):
+ return ['INTERNET_NAME', 'AFFILIATE_INTERNET_NAME',
+ 'INTERNET_NAME_UNRESOLVED', 'AFFILIATE_INTERNET_NAME_UNRESOLVED',
+ 'DOMAIN_NAME', 'AFFILIATE_DOMAIN_NAME',
+ 'IP_ADDRESS',
+ 'PHYSICAL_COORDINATES', 'RAW_RIR_DATA']
+
+ # https://riddler.io/help/api
+ def login(self):
+ params = {
+ 'email': self.opts['username'].encode('raw_unicode_escape').decode("ascii"),
+ 'password': self.opts['password'].encode('raw_unicode_escape').decode("ascii")
+ }
+ headers = {
+ 'Content-Type': 'application/json',
+ }
+
+ res = self.sf.fetchUrl('https://riddler.io/auth/login',
+ postData=json.dumps(params),
+ headers=headers,
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ if res['content'] is None:
+ return
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from F-Secure Riddler: {e}")
+ return
+
+ try:
+ token = data.get('response').get('user').get('authentication_token')
+ except Exception:
+ self.error('Login failed')
+ self.errorState = True
+ return
+
+ if not token:
+ self.error('Login failed')
+ self.errorState = True
+ return
+
+ self.token = token
+
+ # https://riddler.io/help/search
+ def query(self, qry):
+ params = {
+ 'query': qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ 'Authentication-Token': self.token,
+ 'Content-Type': 'application/json',
+ }
+
+ res = self.sf.fetchUrl('https://riddler.io/api/search',
+ postData=json.dumps(params),
+ headers=headers,
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(1)
+
+ if res['code'] in ["400", "401", "402", "403", "500"]:
+ self.error(f"Unexpected HTTP response code {res['code']} from F-Secure Riddler")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from F-Secure Riddler: {e}")
+ return None
+
+ if not data:
+ self.debug(f"No results found for {qry}")
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == 'sfp_fsecure_riddler':
+ self.debug(f"Ignoring {eventName}, from self.")
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.opts['username'] == '' or self.opts['password'] == '':
+ self.error('You enabled sfp_fsecure_riddler but did not set an API username/password!')
+ self.errorState = True
+ return
+
+ if not self.token:
+ self.login()
+
+ if not self.token:
+ self.error('Could not login to F-Secure Riddler')
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ data = None
+
+ if eventName in ['INTERNET_NAME', 'DOMAIN_NAME']:
+ data = self.query("pld:" + eventData)
+ elif eventName == 'IP_ADDRESS':
+ data = self.query("ip:" + eventData)
+
+ if not data:
+ self.info(f"No results found for {eventData}")
+ return
+
+ e = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(e)
+
+ hosts = list()
+ addrs = list()
+ coords = list()
+
+ for result in data:
+ host = result.get('host')
+
+ if not host:
+ continue
+
+ if not self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ continue
+
+ hosts.append(host)
+
+ addr = result.get('addr')
+
+ if addr:
+ addrs.append(addr)
+
+ coord = result.get('cordinates')
+
+ if coord and len(coord) == 2:
+ coords.append(str(coord[0]) + ', ' + str(coord[1]))
+
+ if self.opts['verify'] and len(hosts) > 0:
+ self.info("Resolving " + str(len(set(hosts))) + " domains ...")
+
+ for host in set(hosts):
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ else:
+ evt_type = 'AFFILIATE_INTERNET_NAME'
+
+ if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt_type += '_UNRESOLVED'
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(host, self.opts['_internettlds']):
+ if evt_type.startswith('AFFILIATE'):
+ evt = SpiderFootEvent('AFFILIATE_DOMAIN_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent('DOMAIN_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for addr in set(addrs):
+ if self.sf.validIP(addr):
+ evt = SpiderFootEvent('IP_ADDRESS', addr, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for coord in set(coords):
+ evt = SpiderFootEvent('PHYSICAL_COORDINATES', coord, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_fsecure_riddler class
diff --git a/spiderfoot/modules/sfp_fullcontact.py b/spiderfoot/modules/sfp_fullcontact.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a5e14246651501865bb299a0a66149b371eb6bc
--- /dev/null
+++ b/spiderfoot/modules/sfp_fullcontact.py
@@ -0,0 +1,268 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_fullcontact
+# Purpose: Gather domain and e-mail information from FullContact.com API.
+#
+# Author: Steve Micallef
+#
+# Created: 06/02/2018
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+from datetime import datetime
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_fullcontact(SpiderFootPlugin):
+
+ meta = {
+ 'name': "FullContact",
+ 'summary': "Gather domain and e-mail information from FullContact.com API.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://www.fullcontact.com",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://dashboard.fullcontact.com/api-ref",
+ "https://www.fullcontact.com/developer-portal/",
+ "https://www.fullcontact.com/insights-bundles/",
+ "https://dashboard.fullcontact.com/docs",
+ "https://www.fullcontact.com/faq/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://fullcontact.com",
+ "Register a free account",
+ "Navigate to https://dashboard.fullcontact.com",
+ "Click on 'Get an API Key'",
+ "Verify your account using your contact number",
+ "The API Key will be listed under 'Your API Keys'"
+ ],
+ 'favIcon': "https://1a3asl4eps7u26kl661u3bi9-wpengine.netdna-ssl.com/wp-content/uploads/2019/11/cropped-full-contact-isologo-32x32.png",
+ 'logo': "https://1a3asl4eps7u26kl661u3bi9-wpengine.netdna-ssl.com/wp-content/themes/fc-theme/assets/images/common/full-contact-logo.svg?1574450351",
+ 'description': "Connecting data. Consolidating identities. Applying insights. Amplifying media reach. "
+ "We provide person-centered identity resolution to improve your customer interactions with a simple, "
+ "real-time API integration.\n"
+ "FullContact is a privacy-safe Identity Resolution company building trust between people and brands. "
+ "We deliver the capabilities needed to create tailored customer experiences by unifying data and "
+ "applying insights in the moments that matter.",
+ }
+ }
+
+ opts = {
+ "api_key": "",
+ "max_age_days": "365"
+ }
+
+ optdescs = {
+ "api_key": "FullContact.com API key.",
+ "max_age_days": "Maximum number of age in days for a record before it's considered invalid and not reported."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "EMAILADDR"]
+
+ def producedEvents(self):
+ return [
+ "EMAILADDR",
+ "EMAILADDR_GENERIC",
+ "RAW_RIR_DATA",
+ "PHONE_NUMBER",
+ "GEOINFO",
+ "PHYSICAL_ADDRESS"
+ ]
+
+ def query(self, url, data, failcount=0):
+ headers = {
+ 'Authorization': f"Bearer {self.opts['api_key']}"
+ }
+
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ postData=json.dumps(data),
+ headers=headers
+ )
+
+ if res['code'] in ["401", "400"]:
+ self.error("API key rejected by FullContact")
+ self.errorState = True
+ return None
+
+ if res['code'] == "403":
+ if failcount == 3:
+ self.error("Throttled or other blocking by FullContact")
+ return None
+
+ time.sleep(2)
+ failcount += 1
+ return self.query(url, data, failcount)
+
+ if not res['content']:
+ self.error("No content returned from FullContact")
+ return None
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from FullContact: {e}")
+ return None
+
+ if "updated" in ret and int(self.opts['max_age_days']) > 0:
+ last_dt = datetime.strptime(ret['updated'], '%Y-%m-%d')
+ last_ts = int(time.mktime(last_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * int(self.opts['max_age_days']))
+
+ if last_ts < age_limit_ts:
+ self.debug("FullContact record found but too old.")
+ return None
+
+ return ret
+
+ def queryCompany(self, domain):
+ url = "https://api.fullcontact.com/v3/company.enrich"
+
+ if not domain:
+ return None
+
+ return self.query(url, {"domain": domain})
+
+ def queryPersonByEmail(self, email):
+ url = "https://api.fullcontact.com/v3/person.enrich"
+
+ if not email:
+ return None
+
+ return self.query(url, {'email': email})
+
+ def queryPersonByName(self, name):
+ url = "https://api.fullcontact.com/v3/person.enrich"
+
+ if not name:
+ return None
+
+ return self.query(url, {'fullName': name})
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "EMAILADDR":
+ data = self.queryPersonByEmail(eventData)
+
+ if not data:
+ return
+
+ full_name = data.get('fullName')
+
+ if full_name:
+ e = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {full_name}", self.__name__, event)
+ self.notifyListeners(e)
+
+ return
+
+ if eventName == "DOMAIN_NAME":
+ data = self.queryCompany(eventData)
+
+ if not data:
+ return
+
+ if data.get("details"):
+ data = data['details']
+
+ if data.get("emails"):
+ for r in data['emails']:
+ email = r.get('value')
+
+ if not email:
+ continue
+
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ e = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(e)
+
+ if data.get("phones"):
+ for r in data['phones']:
+ phone = r.get('value')
+
+ if not phone:
+ continue
+
+ e = SpiderFootEvent("PHONE_NUMBER", phone, self.__name__, event)
+ self.notifyListeners(e)
+
+ if data.get("locations"):
+ for r in data['locations']:
+ location = ', '.join([_f for _f in [r.get('city'), r.get('country')] if _f])
+ if location:
+ e = SpiderFootEvent(
+ "GEOINFO",
+ location,
+ self.__name__,
+ event
+ )
+ self.notifyListeners(e)
+
+ if r.get("formatted"):
+ # Seems to contain some junk sometimes
+ if len(r['formatted']) > 10:
+ e = SpiderFootEvent(
+ "PHYSICAL_ADDRESS",
+ r['formatted'],
+ self.__name__,
+ event
+ )
+ self.notifyListeners(e)
+
+ if data.get("keyPeople"):
+ for r in data['keyPeople']:
+ full_name = r.get('fullName')
+ if full_name:
+ e = SpiderFootEvent(
+ "RAW_RIR_DATA",
+ f"Possible full name: {full_name}",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(e)
+
+# End of sfp_fullcontact class
diff --git a/spiderfoot/modules/sfp_fullhunt.py b/spiderfoot/modules/sfp_fullhunt.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ce4f3a80e0f87033619bf2c2bbf8229237d2c85
--- /dev/null
+++ b/spiderfoot/modules/sfp_fullhunt.py
@@ -0,0 +1,244 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_fullhunt
+# Purpose: Identify domain attack surface using FullHunt API.
+#
+# Author:
+#
+# Created: 2021-10-26
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_fullhunt(SpiderFootPlugin):
+
+ meta = {
+ 'name': "FullHunt",
+ 'summary': "Identify domain attack surface using FullHunt API.",
+ 'flags': ['apikey'],
+ 'useCases': ["Passive", "Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://fullhunt.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://api-docs.fullhunt.io/",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://fullhunt.io/",
+ "Register a free account",
+ "Navigate to https://fullhunt.io/user/settings/",
+ "Your API key is listed under 'API Access'"
+ ],
+ 'favIcon': "https://fullhunt.io/static/theme/images/logo/favicon.ico",
+ 'logo': "https://fullhunt.io/static/theme/images/logo/Icon.png",
+ 'description': "Discover, monitor, and secure your attack surface. "
+ "FullHunt delivers the best platform in the market for attack surface security."
+ }
+ }
+
+ opts = {
+ "api_key": "",
+ }
+
+ optdescs = {
+ "api_key": "FullHunt API key.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ ]
+
+ def producedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME_UNRESOLVED",
+ "TCP_PORT_OPEN",
+ "PROVIDER_DNS",
+ "PROVIDER_MAIL",
+ "RAW_RIR_DATA"
+ ]
+
+ def queryDomainDetails(self, qry):
+ """Search for hosts on a domain.
+
+ Args:
+ qry (str): domain name
+
+ Returns:
+ dict: search results
+ """
+ headers = {
+ 'X-API-KEY': self.opts['api_key']
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://fullhunt.io/api/v1/domain/{qry}/details",
+ timeout=30,
+ headers=headers,
+ useragent=self.opts['_useragent']
+ )
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from FullHunt.")
+ return None
+
+ if res['code'] == "400":
+ self.error("Bad Request -- Your request is invalid.")
+ return None
+
+ if res['code'] == "401":
+ self.errorState = True
+ self.error("Unauthorized -- Your API key is wrong.")
+ return None
+
+ if res['code'] == "403":
+ self.errorState = True
+ self.error("Forbidden -- The requested resource is forbidden.")
+ return None
+
+ if res['code'] == "404":
+ self.error("Not Found -- The requested resource could not be found.")
+ return None
+
+ if res['code'] == "429":
+ self.errorState = True
+ self.error("Too Many Requests -- You are sending too many requests.")
+ return None
+
+ try:
+ results = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ return results.get('hosts')
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ res = self.queryDomainDetails(eventData)
+
+ if not res:
+ self.debug(f"Found no results for {eventData}")
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(res), self.__name__, event)
+ self.notifyListeners(e)
+
+ hosts = list()
+ name_servers = list()
+ mail_servers = list()
+
+ for record in res:
+ host = record.get('host')
+
+ if not host:
+ continue
+
+ hosts.append(host)
+
+ dns = record.get('dns')
+ if dns:
+ mx = dns.get('mx')
+ if mx:
+ for mail_server in mx:
+ mail_servers.append(mail_server.rstrip("."))
+
+ ns = dns.get('ns')
+ if ns:
+ for name_server in ns:
+ name_servers.append(name_server.rstrip("."))
+
+ cname = dns.get('cname')
+ if cname:
+ for c in cname:
+ hosts.append(c.rstrip("."))
+
+ network_ports = record.get('network_ports')
+ if network_ports:
+ for port in network_ports:
+ e = SpiderFootEvent("TCP_PORT_OPEN", f"{host}:{port}", self.__name__, event)
+ self.notifyListeners(e)
+
+ for host in set(mail_servers):
+ if not host:
+ continue
+
+ hosts.append(host)
+
+ e = SpiderFootEvent("PROVIDER_MAIL", host, self.__name__, event)
+ self.notifyListeners(e)
+
+ for host in set(name_servers):
+ if not host:
+ continue
+
+ hosts.append(host)
+
+ e = SpiderFootEvent("PROVIDER_DNS", host, self.__name__, event)
+ self.notifyListeners(e)
+
+ for host in set(hosts):
+ if not host:
+ continue
+
+ if host in self.results:
+ continue
+
+ self.results[host] = True
+
+ if self.getTarget().matches(host, includeChildren=True):
+ evt_type = "INTERNET_NAME"
+ else:
+ evt_type = "AFFILIATE_INTERNET_NAME"
+
+ if not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt_type += "_UNRESOLVED"
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_fullhunt class
diff --git a/spiderfoot/modules/sfp_github.py b/spiderfoot/modules/sfp_github.py
new file mode 100644
index 0000000000000000000000000000000000000000..490ebcbc80e9e478299f7557665aab6bd19a03df
--- /dev/null
+++ b/spiderfoot/modules/sfp_github.py
@@ -0,0 +1,282 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_github
+# Purpose: Identifies public code repositories in Github associated with
+# your target.
+#
+# Author: Steve Micallef
+#
+# Created: 21/07/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_github(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Github",
+ 'summary': "Identify associated public code repositories on Github.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Social Media"],
+ 'dataSource': {
+ 'website': "https://github.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://developer.github.com/"
+ ],
+ 'favIcon': "https://github.githubassets.com/favicons/favicon.png",
+ 'logo': "https://github.githubassets.com/favicons/favicon.png",
+ 'description': "GitHub brings together the world's largest community of "
+ "developers to discover, share, and build better software.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'namesonly': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'namesonly': "Match repositories by name only, not by their descriptions. Helps reduce false positives."
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "USERNAME", "SOCIAL_MEDIA"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "GEOINFO", "PUBLIC_CODE_REPO"]
+
+ # Build up repo info for use as an event
+ def buildRepoInfo(self, item):
+ # Get repos matching the name
+ name = item.get('name')
+ if name is None:
+ self.debug("Incomplete Github information found (name).")
+ return None
+
+ html_url = item.get('html_url')
+ if html_url is None:
+ self.debug("Incomplete Github information found (url).")
+ return None
+
+ description = item.get('description')
+ if description is None:
+ self.debug("Incomplete Github information found (description).")
+ return None
+
+ return "\n".join([f"Name: {name}", f"URL: {html_url}", f"Description: {description}"])
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+ srcModuleName = event.module
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Already did a search for {eventData}, skipping.")
+ return
+
+ self.results[eventData] = True
+
+ # Extract name and location from profile
+ if eventName == "SOCIAL_MEDIA":
+ try:
+ network = eventData.split(": ")[0]
+ url = eventData.split(": ")[1].replace("", "").replace(" ", "")
+ except Exception as e:
+ self.debug(f"Unable to parse SOCIAL_MEDIA: {eventData} ({e})")
+ return
+
+ if network != "Github":
+ self.debug(f"Skipping social network profile, {url}, as not a GitHub profile")
+ return
+
+ try:
+ urlParts = url.split("/")
+ username = urlParts[len(urlParts) - 1]
+ except Exception:
+ self.debug(f"Couldn't get a username out of {url}")
+ return
+
+ res = self.sf.fetchUrl(
+ f"https://api.github.com/users/{username}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['content'] is None:
+ return
+
+ try:
+ json_data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return
+
+ if not json_data.get('login'):
+ self.debug(f"{username} is not a valid GitHub profile")
+ return
+
+ full_name = json_data.get('name')
+
+ if not full_name:
+ self.debug(f"{username} is not a valid GitHub profile")
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {full_name}", self.__name__, event)
+ self.notifyListeners(e)
+
+ location = json_data.get('location')
+
+ if location is None:
+ return
+
+ if len(location) < 3 or len(location) > 100:
+ self.debug(f"Skipping likely invalid location: {location}")
+ return
+
+ e = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(e)
+
+ return
+
+ if eventName == "DOMAIN_NAME":
+ username = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ if not username:
+ return
+
+ if eventName == "USERNAME":
+ username = eventData
+
+ self.debug(f"Looking at {username}")
+ failed = False
+
+ # Get all the repositories based on direct matches with the
+ # name identified
+ url = f"https://api.github.com/search/repositories?q={username}"
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ failed = True
+
+ if not failed:
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from GitHub: {e}")
+ ret = None
+
+ if ret is None:
+ self.error(f"Unable to process empty response from Github for: {username}")
+ failed = True
+
+ if not failed:
+ if ret.get('total_count', "0") == "0" or len(ret['items']) == 0:
+ self.debug(f"No Github information for {username}")
+ failed = True
+
+ if not failed:
+ for item in ret['items']:
+ repo_info = self.buildRepoInfo(item)
+ if repo_info is not None:
+ if self.opts['namesonly'] and username != item['name']:
+ continue
+
+ evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info, self.__name__, event)
+ self.notifyListeners(evt)
+
+ # Now look for users matching the name found
+ failed = False
+ url = f"https://api.github.com/search/users?q={username}"
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ failed = True
+
+ if not failed:
+ try:
+ ret = json.loads(res['content'])
+ if ret is None:
+ self.error(f"Unable to process empty response from Github for: {username}")
+ failed = True
+ except Exception:
+ self.error(f"Unable to process invalid response from Github for: {username}")
+ failed = True
+
+ if not failed:
+ if ret.get('total_count', "0") == "0" or len(ret['items']) == 0:
+ self.debug("No Github information for " + username)
+ failed = True
+
+ if not failed:
+ # For each user matching the username, get their repos
+ for item in ret['items']:
+ if item.get('repos_url') is None:
+ self.debug("Incomplete Github information found (repos_url).")
+ continue
+
+ url = item['repos_url']
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch {url}")
+ continue
+
+ try:
+ repret = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Invalid JSON returned from Github: {e}")
+ continue
+
+ if repret is None:
+ self.error(f"Unable to process empty response from Github for: {username}")
+ continue
+
+ for item in repret:
+ if type(item) != dict:
+ self.debug("Encountered an unexpected or empty response from Github.")
+ continue
+
+ repo_info = self.buildRepoInfo(item)
+ if repo_info is not None:
+ if self.opts['namesonly'] and item['name'] != username:
+ continue
+ if eventName == "USERNAME" and "/" + username + "/" not in item.get('html_url', ''):
+ continue
+
+ evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+
+# End of sfp_github class
diff --git a/spiderfoot/modules/sfp_gleif.py b/spiderfoot/modules/sfp_gleif.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c42e51157a01cf39997bf3ec24c81ba5a3ca668
--- /dev/null
+++ b/spiderfoot/modules/sfp_gleif.py
@@ -0,0 +1,311 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_gleif
+# Purpose: Search the Global LEI Index for company information using
+# Global Legal Entity Identifier Foundation (GLEIF) search API.
+#
+# Author:
+#
+# Created: 2021-06-21
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_gleif(SpiderFootPlugin):
+
+ meta = {
+ 'name': "GLEIF",
+ 'summary': "Look up company information from Global Legal Entity Identifier Foundation (GLEIF).",
+ 'flags': [],
+ 'useCases': ["Passive", "Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://search.gleif.org/",
+ 'model': "FREE_NOAUTH_LIMITED",
+ 'references': [
+ "https://www.gleif.org/en/lei-data/gleif-api",
+ "https://api.gleif.org/docs",
+ ],
+ 'favIcon': "https://www.gleif.org/favicon.ico",
+ 'logo': "https://search.gleif.org/static/img/gleif-logo.svg",
+ 'description': "The Global Legal Entity Identifier Foundation (GLEIF) Global LEI Index contains "
+ "historical and current LEI records including related reference data in one authoritative, central repository."
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["COMPANY_NAME", "LEI"]
+
+ def producedEvents(self):
+ return ["COMPANY_NAME", "LEI", "PHYSICAL_ADDRESS", "RAW_RIR_DATA"]
+
+ def searchLegalName(self, qry):
+ """Fuzzy search for legal entity by name
+
+ Args:
+ qry (str): legal entity name
+
+ Returns:
+ dict: search results
+ """
+
+ params = urllib.parse.urlencode({
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'field': "entity.legalName"
+ })
+
+ headers = {
+ 'Accept': 'application/vnd.api+json'
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.gleif.org/api/v1/fuzzycompletions?{params}",
+ timeout=30,
+ headers=headers,
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "429":
+ self.error("You are being rate-limited by GLEIF.")
+ return None
+
+ try:
+ results = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ data = results.get('data')
+ if not data:
+ return None
+ if not len(data):
+ return None
+
+ return data
+
+ def searchAutocompletions(self, qry):
+ """Search for legal entity name autocompletions
+
+ Args:
+ qry (str): legal entity name
+
+ Returns:
+ dict: search results
+ """
+
+ params = urllib.parse.urlencode({
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'field': "fulltext"
+ })
+
+ headers = {
+ 'Accept': 'application/vnd.api+json'
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.gleif.org/api/v1/autocompletions?{params}",
+ timeout=30,
+ headers=headers,
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "429":
+ self.error("You are being rate-limited by GLEIF.")
+ return None
+
+ try:
+ results = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ data = results.get('data')
+ if not data:
+ return None
+ if not len(data):
+ return None
+
+ return data
+
+ def retrieveRecord(self, lei):
+ headers = {
+ 'Accept': 'application/vnd.api+json'
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://api.gleif.org/api/v1/lei-records/{lei}",
+ timeout=self.opts['_fetchtimeout'],
+ headers=headers,
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "404":
+ self.error(f"No record for LEI: {lei}")
+ return None
+
+ if res['code'] == "429":
+ self.error("You are being rate-limited by GLEIF.")
+ return None
+
+ try:
+ results = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ data = results.get('data')
+
+ if not len(data):
+ return None
+ if not data:
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ leis = list()
+
+ if eventName == "LEI":
+ leis.append(eventData)
+ elif eventName == "COMPANY_NAME":
+ self.results[eventData] = True
+ res = self.searchAutocompletions(eventData)
+
+ if res is None:
+ self.debug(f"Found no results for {eventData}")
+ return
+
+ e = SpiderFootEvent("RAW_RIR_DATA", str(res), self.__name__, event)
+ self.notifyListeners(e)
+
+ for record in res:
+ relationships = record.get('relationships')
+ if not relationships:
+ continue
+
+ lei_records = relationships.get('lei-records')
+ if not lei_records:
+ continue
+
+ data = lei_records.get('data')
+ if not data:
+ continue
+
+ lei = data.get('id')
+ if not SpiderFootHelpers.validLEI(lei):
+ continue
+
+ leis.append(lei)
+
+ self.info(f"Found {len(leis)} LEIs matching {eventData}")
+
+ for lei in set(leis):
+ if lei in self.results:
+ continue
+
+ if not SpiderFootHelpers.validLEI(lei):
+ continue
+
+ self.results[lei] = True
+
+ e = SpiderFootEvent("LEI", lei, self.__name__, event)
+ self.notifyListeners(e)
+
+ self.results[lei] = True
+
+ res = self.retrieveRecord(lei)
+ if not res:
+ self.debug(f"Found no results for {eventData}")
+ continue
+
+ attributes = res.get('attributes')
+ if not attributes:
+ continue
+
+ entity = attributes.get('entity')
+ if not entity:
+ continue
+
+ legal_name = entity.get('legalName')
+ if legal_name:
+ entity_name = legal_name.get('value')
+ if entity_name:
+ e = SpiderFootEvent("COMPANY_NAME", entity_name, self.__name__, event)
+ self.notifyListeners(e)
+
+ addresses = list()
+
+ address = entity.get('legalAddress')
+ if address.get('addressLines'):
+ address_lines = ', '.join(filter(None, address.get('addressLines')))
+ location = ', '.join(
+ filter(
+ None,
+ [
+ address_lines,
+ address.get('city'),
+ address.get('region'),
+ address.get('country'),
+ address.get('postalCode')
+ ]
+ )
+ )
+
+ if location:
+ addresses.append(location)
+
+ address = entity.get('headquartersAddress')
+ if address.get('addressLines'):
+ address_lines = ', '.join(filter(None, address.get('addressLines')))
+ location = ', '.join(
+ filter(
+ None,
+ [
+ address_lines,
+ address.get('city'),
+ address.get('region'),
+ address.get('country'),
+ address.get('postalCode')
+ ]
+ )
+ )
+
+ if location:
+ addresses.append(location)
+
+ for address in set(addresses):
+ e = SpiderFootEvent("PHYSICAL_ADDRESS", address, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_gleif class
diff --git a/spiderfoot/modules/sfp_google_tag_manager.py b/spiderfoot/modules/sfp_google_tag_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..984ebdfd4812f30d16fac3e05a02f5ce12351ffc
--- /dev/null
+++ b/spiderfoot/modules/sfp_google_tag_manager.py
@@ -0,0 +1,184 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_google_tag_manager
+# Purpose: Search Google Tag Manager (GTM) for hosts sharing the same GTM code.
+#
+# Author:
+#
+# Created: 2023-10-29
+# Copyright: (c) bcoles 2023
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_google_tag_manager(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Google Tag Manager",
+ 'summary': "Search Google Tag Manager (GTM) for hosts sharing the same GTM code.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://tagmanager.google.com",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://marketingplatform.google.com/about/tag-manager/",
+ "https://developers.google.com/tag-manager/quickstart",
+ "https://developers.google.com/tag-manager/devguide"
+ ],
+ 'favIcon': "https://google.com/favicon.ico",
+ 'logo': "https://google.com/favicon.ico",
+ 'description': "Manage all your website tags without editing code. Google Tag Manager "
+ "delivers simple, reliable, easily integrated tag management solutions for free."
+ }
+ }
+
+ opts = {
+ "verify": True
+ }
+
+ optdescs = {
+ "verify": "Verify identified hostnames resolve to an IP address."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['WEB_ANALYTICS_ID']
+
+ def producedEvents(self):
+ return [
+ 'DOMAIN_NAME',
+ 'INTERNET_NAME',
+ 'AFFILIATE_DOMAIN_NAME',
+ 'AFFILIATE_INTERNET_NAME',
+ ]
+
+ # from: https://stackoverflow.com/a/43211062
+ def is_valid_hostname(self, hostname: str = None) -> bool:
+ if not hostname:
+ return False
+ if len(hostname) > 255:
+ return False
+
+ hostname = hostname.rstrip(".")
+ allowed = re.compile("(?!-)[A-Z0-9-_]{1,63}(? set:
+ if not tag_id:
+ return None
+
+ params = urllib.parse.urlencode({
+ 'id': tag_id,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://googletagmanager.com/gtm.js?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] != "200":
+ self.debug(f"Invalid GTM tag id: {tag_id}")
+ return None
+
+ data = res['content']
+
+ if not data:
+ self.debug(f"Invalid GTM tag id: {tag_id}")
+ return None
+
+ hosts = list()
+
+ for host in re.findall(r'"map","key","(.+?)"', data):
+ if '.' not in host:
+ continue
+ if self.is_valid_hostname(host):
+ hosts.append(host)
+
+ for host in re.findall(r',"arg1":"(.+?)"', data):
+ if '.' not in host:
+ continue
+ if self.is_valid_hostname(host):
+ hosts.append(host)
+
+ for url in SpiderFootHelpers.extractUrlsFromText(str(data).replace("\\/", "/")):
+ host = self.sf.urlFQDN(url)
+ if not host:
+ continue
+ if '.' not in host:
+ continue
+ hosts.append(host)
+
+ return set(hosts)
+
+ def handleEvent(self, event):
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ if self.errorState:
+ return
+
+ if event.data in self.results:
+ return
+
+ self.results[event.data] = True
+
+ try:
+ network = event.data.split(": ")[0]
+ tag_id = event.data.split(": ")[1]
+ except Exception as e:
+ self.error(f"Unable to parse WEB_ANALYTICS_ID: {event.data} ({e})")
+ return
+
+ if network != 'Google Tag Manager':
+ return
+
+ hosts = self.queryGoogleTagId(tag_id)
+
+ if not hosts:
+ self.info(f"No hosts found for {tag_id}")
+ return
+
+ self.info(f"Retrieved {len(hosts)} results")
+
+ for host in hosts:
+ # we ignore unresolved hosts due to large number of false positives
+ if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Potential host name '{host}' could not be resolved")
+ continue
+
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ else:
+ evt_type = 'AFFILIATE_INTERNET_NAME'
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(host, self.opts['_internettlds']):
+ if evt_type.startswith('AFFILIATE'):
+ evt_type = 'AFFILIATE_DOMAIN_NAME'
+ else:
+ evt_type = 'DOMAIN_NAME'
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_google_tag_manager class
diff --git a/spiderfoot/modules/sfp_googlemaps.py b/spiderfoot/modules/sfp_googlemaps.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6940c5aea259271c645c07e71e43594826bf391
--- /dev/null
+++ b/spiderfoot/modules/sfp_googlemaps.py
@@ -0,0 +1,165 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_googlemaps
+# Purpose: SpiderFoot plug-in to identify historical certificates for a domain
+# from googlemaps.sh, and from this identify hostnames.
+#
+# Author: Steve Micallef
+#
+# Created: 18/03/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_googlemaps(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Google Maps",
+ 'summary': "Identifies potential physical addresses and latitude/longitude coordinates.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://cloud.google.com/maps-platform/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://developers.google.com/maps/documentation/?_ga=2.135220017.1220421370.1587340370-900596925.1587340370"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://cloud.google.com/maps-platform/",
+ "Register a free Google account",
+ "Click on 'Get Started'",
+ "Click on 'API'",
+ "Select the type of API",
+ "Navigate to https://console.cloud.google.com/apis/credentials",
+ "Click on 'Credentials'",
+ "The API Key will be listed under 'API Keys'"
+ ],
+ 'favIcon': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/cloud/images/favicons/onecloud/favicon.ico",
+ 'logo': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/cloud/images/cloud-logo.svg",
+ 'description': "Explore where real-world insights and immersive location experiences can take your business.\n"
+ "Build with reliable, comprehensive data for over 200 countries and territories.\n"
+ "has been done here. If line breaks are needed for breaking up\n"
+ "Scale confidently, backed by our infrastructure.",
+ }
+ }
+
+ opts = {
+ "api_key": ""
+ }
+ optdescs = {
+ "api_key": "Google Geocoding API Key."
+ }
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ['DOMAIN_NAME', 'PHYSICAL_ADDRESS']
+
+ def producedEvents(self):
+ return ["PHYSICAL_ADDRESS", "PHYSICAL_COORDINATES", "RAW_RIR_DATA"]
+
+ def query(self, address):
+ params = urllib.parse.urlencode({
+ 'key': self.opts['api_key'],
+ 'address': address.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://maps.googleapis.com/maps/api/geocode/json?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['content'] is None:
+ self.info(f"No location info found for {address}")
+ return None
+
+ return res
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ res = self.query(eventData)
+
+ if not res:
+ self.debug(f"No information found for {eventData}")
+ return
+
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA",
+ res['content'],
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ try:
+ data = json.loads(res['content'])['results'][0]
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return
+
+ if srcModuleName == "sfp_googlemaps":
+ return
+
+ geometry = data.get('geometry')
+ if geometry:
+ location = data.get('location')
+ if location:
+ lat = location.get('lat')
+ lng = location.get('lng')
+ if lat and lng:
+ evt = SpiderFootEvent(
+ "PHYSICAL_COORDINATES",
+ f"{lat},{lng}",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ formatted_address = data.get('formatted_address')
+ if formatted_address:
+ evt = SpiderFootEvent(
+ "PHYSICAL_ADDRESS",
+ data['formatted_address'],
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_googlemaps class
diff --git a/spiderfoot/modules/sfp_googleobjectstorage.py b/spiderfoot/modules/sfp_googleobjectstorage.py
new file mode 100644
index 0000000000000000000000000000000000000000..81d51833c146122cf5b466ee1ade469b4c5255f0
--- /dev/null
+++ b/spiderfoot/modules/sfp_googleobjectstorage.py
@@ -0,0 +1,200 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_googleobjectstorage
+# Purpose: SpiderFoot plug-in for identifying potential Google Object Storage
+# buckets related to the target.
+#
+# Author: Steve Micallef
+#
+# Created: 24/01/2020
+# Copyright: (c) Steve Micallef 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import random
+import threading
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_googleobjectstorage(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Google Object Storage Finder",
+ 'summary': "Search for potential Google Object Storage buckets associated with the target and attempt to list their contents.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Crawling and Scanning"],
+ 'dataSource': {
+ 'website': "https://cloud.google.com/storage",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'favIcon': 'https://www.gstatic.com/devrel-devsite/prod/v4c1e9ea53f4457a5de1027b4eeb4608c1000a427e20261ba1771dd3fc26d5df8/cloud/images/favicons/onecloud/favicon.ico',
+ 'logo': 'https://www.gstatic.com/devrel-devsite/prod/v4c1e9ea53f4457a5de1027b4eeb4608c1000a427e20261ba1771dd3fc26d5df8/cloud/images/cloud-logo.svg',
+ 'description': "Object storage for companies of all sizes."
+ "Secure, durable, and with low latency. Store any amount of data."
+ "Retrieve it as often as you'd like."
+ }
+ }
+
+ # Default options
+ opts = {
+ "suffixes": "test,dev,web,beta,bucket,space,files,content,data,prod,staging,production,stage,app,media,development,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data,-prod,-staging,-production,-stage,-app,-media,-development",
+ "_maxthreads": 20
+ }
+
+ # Option descriptions
+ optdescs = {
+ "suffixes": "List of suffixes to append to domains tried as bucket names",
+ "_maxthreads": "Maximum threads"
+ }
+
+ results = None
+ gosresults = dict()
+ lock = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.gosresults = dict()
+ self.results = self.tempStorage()
+ self.lock = threading.Lock()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["CLOUD_STORAGE_BUCKET", "CLOUD_STORAGE_BUCKET_OPEN"]
+
+ def checkSite(self, url):
+ res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot", noLog=True)
+
+ if not res['content']:
+ return
+
+ if "NoSuchBucket" in res['content']:
+ self.debug(f"Not a valid bucket: {url}")
+ return
+
+ # Bucket found
+ if res['code'] in ["301", "302", "200"]:
+ # Bucket has files
+ if "ListBucketResult" in res['content']:
+ with self.lock:
+ self.gosresults[url] = res['content'].count("")
+ else:
+ # Bucket has no files
+ with self.lock:
+ self.gosresults[url] = 0
+
+ def threadSites(self, siteList):
+ self.gosresults = dict()
+ running = True
+ i = 0
+ t = []
+
+ for site in siteList:
+ if self.checkForStop():
+ return None
+
+ self.info("Spawning thread to check bucket: " + site)
+ tname = str(random.SystemRandom().randint(0, 999999999))
+ t.append(threading.Thread(name='thread_sfp_googleobjectstorage_' + tname,
+ target=self.checkSite, args=(site,)))
+ t[i].start()
+ i += 1
+
+ # Block until all threads are finished
+ while running:
+ found = False
+ for rt in threading.enumerate():
+ if rt.name.startswith("thread_sfp_googleobjectstorage_"):
+ found = True
+
+ if not found:
+ running = False
+
+ time.sleep(0.25)
+
+ # Return once the scanning has completed
+ return self.gosresults
+
+ def batchSites(self, sites):
+ i = 0
+ res = list()
+ siteList = list()
+
+ for site in sites:
+ if i >= self.opts['_maxthreads']:
+ data = self.threadSites(siteList)
+ if data is None:
+ return res
+
+ for ret in list(data.keys()):
+ if data[ret]:
+ # bucket:filecount
+ res.append(ret + ":" + str(data[ret]))
+ i = 0
+ siteList = list()
+
+ siteList.append(site)
+ i += 1
+
+ return res
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName == "LINKED_URL_EXTERNAL":
+ if ".storage.googleapis.com" in eventData:
+ b = self.sf.urlFQDN(eventData)
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", b, self.__name__, event)
+ self.notifyListeners(evt)
+ return
+
+ targets = [eventData.replace('.', '')]
+ kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+ if kw:
+ targets.append(kw)
+
+ urls = list()
+ for t in targets:
+ suffixes = [''] + self.opts['suffixes'].split(',')
+ for s in suffixes:
+ if self.checkForStop():
+ return
+
+ b = t + s + ".storage.googleapis.com"
+ url = "https://" + b
+ urls.append(url)
+
+ # Batch the scans
+ ret = self.batchSites(urls)
+ for b in ret:
+ bucket = b.split(":")
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", bucket[0] + ":" + bucket[1], self.__name__, event)
+ self.notifyListeners(evt)
+ if bucket[2] != "0":
+ bucketname = bucket[1].replace("//", "")
+ evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET_OPEN", bucketname + ": " + bucket[2] + " files found.",
+ self.__name__, evt)
+ self.notifyListeners(evt)
+
+
+# End of sfp_googleobjectstorage class
diff --git a/spiderfoot/modules/sfp_googlesafebrowsing.py b/spiderfoot/modules/sfp_googlesafebrowsing.py
new file mode 100644
index 0000000000000000000000000000000000000000..596b883156f58d118e94adb78fbf038164811d6d
--- /dev/null
+++ b/spiderfoot/modules/sfp_googlesafebrowsing.py
@@ -0,0 +1,220 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_googlesafebrowsing
+# Purpose: SpiderFoot plug-in to check if the URL is included on any of the
+# Google Safe Browsing lists
+#
+# Author: Filip Aleksić
+#
+# Created: 2020-08-18
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_googlesafebrowsing(SpiderFootPlugin):
+
+ meta = {
+ "name": "Google SafeBrowsing",
+ "summary": "Check if the URL is included on any of the Safe Browsing lists.",
+ 'flags': ["slow", "apikey"],
+ "useCases": ["Passive", "Investigate"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://developers.google.com/safe-browsing/v4/lookup-api",
+ "model": "FREE_AUTH_UNLIMITED",
+ "references": [
+ "https://developers.google.com/safe-browsing/v4/reference/rest"
+ ],
+ "apiKeyInstructions": [
+ "Visit https://console.developers.google.com/",
+ "Register a free Google account or sign in",
+ "Create or select existing Google Developer Console project",
+ "Go to the Cloud Console API Library https://console.cloud.google.com/apis/library",
+ "From the projects list, select the project you want to use",
+ "In the API Library select 'Safe Browsing APIs'",
+ "On the API page, click ENABLE",
+ "Navigate to the APIs & Services→Credentials panel in Cloud Console",
+ "Select Create credentials, then select API key from the dropdown menu",
+ "The API key created dialog box displays your newly created key",
+ ],
+ "favIcon": "https://www.gstatic.com/devrel-devsite/prod/v1241c04ebcb2127897d6c18221acbd64e7ed5c46e5217fd83dd808e592c47bf6/developers/images/favicon.png",
+ "logo": "https://developers.google.com/safe-browsing/images/SafeBrowsing_Icon.png",
+ "description": "The Safe Browsing APIs (v4) let your client applications check URLs "
+ "against Google's constantly updated lists of unsafe web resources. "
+ "Any URL found on a Safe Browsing list is considered unsafe.",
+ },
+ }
+
+ opts = {"api_key": ""}
+
+ optdescs = {
+ "api_key": "Google Safe Browsing API key.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "IP_ADDRESS",
+ "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_IPADDR",
+ "CO_HOSTED_SITE",
+ ]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return [
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ "RAW_RIR_DATA",
+ ]
+
+ def query(self, qry):
+
+ headers = {"Content-Type": "application/json"}
+ url = (
+ "https://safebrowsing.googleapis.com/v4/threatMatches"
+ f":find?key={self.opts['api_key']}"
+ )
+ payload = {
+ "client": {"clientId": "SpiderFoot", "clientVersion": "3.2"},
+ "threatInfo": {
+ "threatTypes": [
+ "THREAT_TYPE_UNSPECIFIED",
+ "MALWARE",
+ "SOCIAL_ENGINEERING",
+ "UNWANTED_SOFTWARE",
+ "POTENTIALLY_HARMFUL_APPLICATION",
+ ],
+ "platformTypes": ["PLATFORM_TYPE_UNSPECIFIED", "ANY_PLATFORM"],
+ "threatEntryTypes": [
+ "THREAT_ENTRY_TYPE_UNSPECIFIED",
+ "URL",
+ "EXECUTABLE",
+ ],
+ "threatEntries": [
+ {
+ "url": qry.encode("raw_unicode_escape").decode(
+ "ascii", errors="replace"
+ )
+ }
+ ],
+ },
+ }
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts["_fetchtimeout"],
+ useragent=self.opts["_useragent"],
+ headers=headers,
+ postData=json.dumps(payload),
+ )
+
+ if res["code"] == "400":
+ self.error("Invalid request payload on Google Safe Browsing API")
+ self.errorState = True
+ return None
+
+ if res["code"] == "429":
+ self.error("Reaching rate limit on Google Safe Browsing API")
+ self.errorState = True
+ return None
+
+ if res["code"] == "403":
+ self.error(
+ "Permission denied, invalid API key on Google Safe Browsing API"
+ )
+ self.errorState = True
+ return None
+
+ if res["code"] in ["500", "503", "504"]:
+ self.error(
+ "Google Safe Browsing API is having some troubles or unavailable."
+ )
+ self.errorState = True
+ return None
+
+ try:
+ info = json.loads(res["content"])
+ if info == {}:
+ self.info("No Google Safe Browsing matches found for " + qry)
+ return None
+
+ except Exception as e:
+ self.error(f"Error processing JSON response from SHODAN: {e}")
+ return None
+
+ return info
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ "You enabled sfp_googlesafebrowsing but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ evtType = ""
+ if eventName in ["IP_ADDRESS", "AFFILIATE_IPADDR"]:
+ if eventName == "IP_ADDRESS":
+ evtType = "MALICIOUS_IPADDR"
+ else:
+ evtType = "MALICIOUS_AFFILIATE_IPADDR"
+
+ if eventName in ["INTERNET_NAME", "CO_HOSTED_SITE", "AFFILIATE_INTERNET_NAME"]:
+ if eventName == "INTERNET_NAME":
+ evtType = "MALICIOUS_INTERNET_NAME"
+ if eventName == "AFFILIATE_INTERNET_NAME":
+ evtType = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ if eventName == "CO_HOSTED_SITE":
+ evtType = "MALICIOUS_COHOST"
+
+ rec = self.query(eventData)
+
+ if rec is None:
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(rec), self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(
+ evtType, "Google SafeBrowsing [" + eventData + "]", self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+
+# End of sfp_googlesafebrowsing class
diff --git a/spiderfoot/modules/sfp_googlesearch.py b/spiderfoot/modules/sfp_googlesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e9e517fed1e7815f107354f116f4da9c1203742
--- /dev/null
+++ b/spiderfoot/modules/sfp_googlesearch.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_googlesearch
+# Purpose: Searches Google for content related to the domain in question.
+#
+# Author: Steve Micallef
+#
+# Created: 07/05/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_googlesearch(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Google",
+ 'summary': "Obtain information from the Google Custom Search API to identify sub-domains and links.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://developers.google.com/custom-search",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://developers.google.com/custom-search/v1",
+ "https://developers.google.com/custom-search/docs/overview",
+ "https://cse.google.com/cse"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://developers.google.com/custom-search/v1/introduction",
+ "Register a free Google account",
+ "Click on 'Get A Key'",
+ "Connect a Project",
+ "The API Key will be listed under 'YOUR API KEY'"
+ ],
+ 'favIcon': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/developers/images/favicon.png",
+ 'logo': "https://www.gstatic.com/devrel-devsite/prod/v2210deb8920cd4a55bd580441aa58e7853afc04b39a9d9ac4198e1cd7fbe04ef/developers/images/favicon.png",
+ 'description': "Google Custom Search enables you to create a search engine for your website, your blog, or a collection of websites. "
+ "You can configure your engine to search both web pages and images. "
+ "You can fine-tune the ranking, add your own promotions and customize the look and feel of the search results. "
+ "You can monetize the search by connecting your engine to your Google AdSense account.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "cse_id": "013611106330597893267:tfgl3wxdtbp"
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "Google API Key for Google search.",
+ "cse_id": "Google Custom Search Engine ID."
+ }
+
+ # Target
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["LINKED_URL_INTERNAL", "RAW_RIR_DATA"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_googlesearch but did not set a Google API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug("Already did a search for " + eventData + ", skipping.")
+ return
+
+ self.results[eventData] = True
+
+ # Sites hosted on the domain
+ res = self.sf.googleIterate(
+ searchString="site:" + eventData,
+ opts={
+ "timeout": self.opts["_fetchtimeout"],
+ "useragent": self.opts["_useragent"],
+ "api_key": self.opts["api_key"],
+ "cse_id": self.opts["cse_id"],
+ },
+ )
+ if res is None:
+ # Failed to talk to the Google API or no results returned
+ return
+
+ urls = res["urls"]
+ new_links = list(set(urls) - set(self.results.keys()))
+
+ # Add new links to results
+ for link in new_links:
+ self.results[link] = True
+
+ internal_links = [
+ link for link in new_links if self.sf.urlFQDN(link).endswith(eventData)
+ ]
+ for link in internal_links:
+ self.debug("Found a link: " + link)
+
+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if internal_links:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(res), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_googlesearch class
diff --git a/spiderfoot/modules/sfp_gravatar.py b/spiderfoot/modules/sfp_gravatar.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8a2a2a7169903bdedba7a660639a4975886d664
--- /dev/null
+++ b/spiderfoot/modules/sfp_gravatar.py
@@ -0,0 +1,197 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_gravatar
+# Purpose: SpiderFoot plug-in to search Gravatar API for an email address
+# and retrieve user information, including username, name, phone
+# numbers, additional email addresses, and social media usernames.
+#
+# Author:
+#
+# Created: 2019-05-26
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import hashlib
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_gravatar(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Gravatar",
+ 'summary': "Retrieve user information from Gravatar API.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Social Media"],
+ 'dataSource': {
+ 'website': "https://secure.gravatar.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://secure.gravatar.com/site/implement/"
+ ],
+ 'favIcon': "https://secure.gravatar.com/favicon.ico",
+ 'logo': "https://secure.gravatar.com/favicon.ico",
+ 'description': "Your Gravatar is an image that follows you from site to site "
+ "appearing beside your name when you do things like comment or post on a blog.\n"
+ "A Gravatar is a Globally Recognized Avatar. You upload it and create your profile just once, "
+ "and then when you participate in any Gravatar-enabled site, your Gravatar image will automatically follow you there.",
+ }
+ }
+
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ results = None
+ reportedUsers = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.reportedUsers = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['EMAILADDR']
+
+ # What events this module produces
+ def producedEvents(self):
+ return ['RAW_RIR_DATA', 'USERNAME',
+ 'EMAILADDR', 'EMAILADDR_GENERIC', 'PHONE_NUMBER', 'GEOINFO',
+ 'ACCOUNT_EXTERNAL_OWNED', 'SOCIAL_MEDIA']
+
+ # Query Gravatar API for the specified email address
+ # https://secure.gravatar.com/site/implement/
+ # https://secure.gravatar.com/site/implement/profiles/
+ def query(self, qry):
+ email_hash = hashlib.md5(qry.encode('utf-8', errors='replace').lower()).hexdigest() # noqa: DUO130
+ output = 'json'
+
+ res = self.sf.fetchUrl("https://secure.gravatar.com/" + email_hash + '.' + output,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ self.debug('No response from gravatar.com')
+ return None
+
+ if res['code'] != '200':
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if data.get('entry') is None or len(data.get('entry')) == 0:
+ return None
+
+ return data.get('entry')[0]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ data = self.query(eventData)
+
+ if data is None:
+ self.debug("No user information found for " + eventData)
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('preferredUsername') is not None:
+ un = data.get('preferredUsername')
+ evt = SpiderFootEvent("USERNAME", un, self.__name__, event)
+ self.notifyListeners(evt)
+ self.reportedUsers[un] = True
+
+ names = list()
+ if data.get('name') is not None:
+ if type(data.get('name')) != list:
+ names.append(data.get('name'))
+ else:
+ names = data.get('name')
+
+ for name in names:
+ full_name = name.get('formatted')
+ if full_name:
+ evt = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {full_name}", self.__name__, event)
+ self.notifyListeners(evt)
+
+ # TODO: re-enable once location validation is implemented
+ # location can not be trusted
+ # if data.get('currentLocation') is not None:
+ # location = data.get('currentLocation')
+ # if len(location) < 3 or len(location) > 100:
+ # self.debug("Skipping likely invalid location.")
+ # else:
+ # evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ # self.notifyListeners(evt)
+
+ if data.get('phoneNumbers') is not None:
+ for number in data.get('phoneNumbers'):
+ if number.get('value') is not None:
+ evt = SpiderFootEvent("PHONE_NUMBER", number.get('value'), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('emails') is not None:
+ for email in data.get('emails'):
+ em = email.get('value')
+ if not em:
+ continue
+ if SpiderFootHelpers.validEmail(em) and em != eventData:
+ if em.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ evt = SpiderFootEvent(evttype, em, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('ims') is not None:
+ for im in data.get('ims'):
+ v = im.get('value')
+ if v is None:
+ continue
+ t = im.get('type').capitalize() + " (Instant Messenger)\n" + v
+ evt = SpiderFootEvent("ACCOUNT_EXTERNAL_OWNED", t, self.__name__, event)
+ self.notifyListeners(evt)
+ if v not in self.reportedUsers:
+ evt = SpiderFootEvent("USERNAME", v, self.__name__, event)
+ self.notifyListeners(evt)
+ self.reportedUsers[v] = True
+
+ if data.get('accounts') is not None:
+ for account in data.get('accounts'):
+ url = account.get('url')
+ platform = account.get('shortname')
+ if platform is not None and url is not None:
+ t = platform.capitalize() + ": " + url + " "
+ evt = SpiderFootEvent("SOCIAL_MEDIA", t, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_gravatar class
diff --git a/spiderfoot/modules/sfp_grayhatwarfare.py b/spiderfoot/modules/sfp_grayhatwarfare.py
new file mode 100644
index 0000000000000000000000000000000000000000..b04b820b7b57fd1d673903be87e7f708e770fb4b
--- /dev/null
+++ b/spiderfoot/modules/sfp_grayhatwarfare.py
@@ -0,0 +1,182 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_grayhatwarfare
+# Purpose: Find bucket names matching the keyword extracted from a domain from Grayhat API.
+#
+# Author:
+#
+# Created: 24-01-2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_grayhatwarfare(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Grayhat Warfare",
+ 'summary': "Find bucket names matching the keyword extracted from a domain from Grayhat API.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://buckets.grayhatwarfare.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://buckets.grayhatwarfare.com/docs/api/v1"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://grayhatwarfare.com/register",
+ "Register an account",
+ "Visit https://grayhatwarfare.com/account/settings",
+ "Your API key is listed under 'Api Key'",
+ ],
+ 'favIcon': "https://buckets.grayhatwarfare.com/assets/template/images/favicon.png",
+ 'logo': "https://buckets.grayhatwarfare.com/assets/images/logo/logo-sm.png",
+ 'description': "It is a searchable database of open buckets."
+ "Has up to million results of each bucket."
+ "Full text search with binary logic (can search for keywords and also stopwords)",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': '',
+ 'per_page': 1000,
+ 'max_pages': 2,
+ 'pause': 1
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': 'Grayhat Warfare API key.',
+ 'per_page': 'Maximum number of results per page (Max: 1000).',
+ 'max_pages': 'Maximum number of pages to fetch.',
+ 'pause': 'Number of seconds to wait between each API call.'
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ 'CLOUD_STORAGE_BUCKET',
+ 'CLOUD_STORAGE_BUCKET_OPEN',
+ 'RAW_RIR_DATA'
+ ]
+
+ # Query Grayhat Warfare
+ def query(self, keyword, start):
+ params = urllib.parse.urlencode({
+ 'keywords': keyword.encode('raw_unicode_escape'),
+ 'access_token': self.opts['api_key']
+ })
+
+ headers = {
+ 'Accept': 'application/json',
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://buckets.grayhatwarfare.com/api/v1/buckets/{start}/{self.opts['per_page']}?{params}",
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent'],
+ verify=True
+ )
+
+ time.sleep(self.opts['pause'])
+
+ if res['code'] != "200":
+ self.error("Unable to fetch data from Grayhat Warfare API.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.debug('No response from Grayhat Warfare API.')
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_grayhatwarfare but did not set an API key!")
+ self.errorState = True
+ return
+
+ currentIndex = 0
+ currentPage = 0
+ maxPages = self.opts['max_pages']
+ perPage = self.opts['per_page']
+
+ keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
+
+ while currentPage < maxPages:
+ currentIndex = currentPage * perPage
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ break
+
+ data = self.query(keyword=keyword, start=currentIndex)
+
+ if not data:
+ return
+
+ for row in data.get('buckets'):
+ bucketName = row.get('bucket')
+ bucketKeyword = bucketName.split('.')[0]
+ self.debug(bucketKeyword)
+ if bucketKeyword.startswith(keyword) or bucketKeyword.endswith(keyword):
+ evt = SpiderFootEvent('CLOUD_STORAGE_BUCKET', bucketName, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('CLOUD_STORAGE_BUCKET_OPEN', f"{bucketName}: {row.get('fileCount')} files found.", self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(row), self.__name__, event)
+ self.notifyListeners(evt)
+
+ currentPage += 1
+ if data.get('buckets_count') < perPage:
+ break
+
+# End of sfp_grayhatwarfare class
diff --git a/spiderfoot/modules/sfp_greensnow.py b/spiderfoot/modules/sfp_greensnow.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e4cb27a0f78c3303850f3fde9eb127dc9d98686
--- /dev/null
+++ b/spiderfoot/modules/sfp_greensnow.py
@@ -0,0 +1,185 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_greensnow
+# Purpose: Checks if an IP address or netblock is malicious according to greensnow.co.
+#
+# Author: steve@binarypool.com
+#
+# Created: 16/05/2020
+# Copyright: (c) Steve Micallef, 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_greensnow(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Greensnow",
+ 'summary': "Check if a netblock or IP address is malicious according to greensnow.co.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://greensnow.co/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://blocklist.greensnow.co/greensnow.txt",
+ "https://greensnow.co/faq"
+ ],
+ 'favIcon': "https://greensnow.co/favicon.ico",
+ 'logo': "https://greensnow.co/img/logo.png",
+ 'description': "GreenSnow is a team consisting of the best specialists in computer security, "
+ "we harvest a large number of IPs from different computers located around the world. "
+ "GreenSnow is comparable with SpamHaus.org for attacks of any kind except for spam. "
+ "Our list is updated automatically and you can withdraw at any time your IP address if it has been listed.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18,
+ 'checknetblocks': True,
+ 'checksubnets': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliate IP addresses?",
+ 'cacheperiod': "Hours to cache list data before re-fetching.",
+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'AFFILIATE_IPADDR',
+ 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER',
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ ]
+
+ def query(self, qry, targetType):
+ cid = "_greensnow"
+ url = "https://blocklist.greensnow.co/greensnow.txt"
+
+ data = dict()
+ data["content"] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))
+
+ if data["content"] is None:
+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if data["code"] != "200":
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ if data["content"] is None:
+ self.error(f"Unable to fetch {url}")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("sfmal_" + cid, data['content'])
+
+ for line in data["content"].split('\n'):
+ ip = line.strip().lower()
+
+ if targetType == "netblock":
+ try:
+ if IPAddress(ip) in IPNetwork(qry):
+ self.debug(f"{ip} found within netblock/subnet {qry} in greensnow.co list.")
+ return f"https://greensnow.co/view/{ip}"
+ except Exception as e:
+ self.debug(f"Error encountered parsing: {e}")
+ continue
+
+ if targetType == "ip":
+ if qry.lower() == ip:
+ self.debug(f"{qry} found in greensnow.co list.")
+ return f"https://greensnow.co/view/{ip}"
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with greensnow.co")
+
+ url = self.query(eventData, targetType)
+
+ if not url:
+ return
+
+ text = f"greensnow.co [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_greensnow class
diff --git a/spiderfoot/modules/sfp_grep_app.py b/spiderfoot/modules/sfp_grep_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..36814187b2622f84871f3f67086e4c16e8c557a9
--- /dev/null
+++ b/spiderfoot/modules/sfp_grep_app.py
@@ -0,0 +1,239 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_grep_app
+# Purpose: Searches grep.app API for domains, URLs and emails related to the
+# specified domain.
+#
+# Author:
+#
+# Created: 2020-04-12
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import math
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_grep_app(SpiderFootPlugin):
+
+ meta = {
+ 'name': "grep.app",
+ 'summary': "Search grep.app API for links and emails related to the specified domain.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://grep.app/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [],
+ 'favIcon': "https://grep.app/favicon-16x16.png",
+ 'logo': "https://grep.app/apple-touch-icon.png",
+ 'description': "grep.app searches code from over a half million public repositories on GitHub.\n"
+ "It searches for the exact string you enter, including any punctuation or other characters.\n"
+ "You can also search by regular expression, using the RE2 syntax.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'max_pages': 20,
+ 'dns_resolve': True,
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'max_pages': "Maximum number of pages of results to fetch.",
+ 'dns_resolve': "DNS resolve each identified domain."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ def producedEvents(self):
+ return ["EMAILADDR", "EMAILADDR_GENERIC", "DOMAIN_NAME",
+ "INTERNET_NAME", "RAW_RIR_DATA",
+ "INTERNET_NAME_UNRESOLVED", "LINKED_URL_INTERNAL"]
+
+ def query(self, qry, page):
+ params = {
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'page': str(page)
+ }
+
+ res = self.sf.fetchUrl("https://grep.app/api/search?" + urllib.parse.urlencode(params),
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == 'sfp_grep_app':
+ self.debug("Ignoring " + eventData + ", from self.")
+ return
+
+ hosts = list()
+ page = 1
+ per_page = 10
+ pages = self.opts['max_pages']
+ while page <= pages:
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ res = self.query(eventData, page)
+
+ if res is None:
+ return
+
+ facets = res.get('facets')
+
+ if facets is None:
+ return
+
+ count = facets.get('count')
+
+ if count is None:
+ return
+
+ last_page = math.ceil(count / per_page)
+
+ if last_page is None:
+ pages = 0
+
+ if last_page < pages:
+ pages = last_page
+
+ self.info("Parsing page " + str(page) + " of " + str(pages))
+ page += 1
+
+ hits = res.get('hits')
+
+ if hits is None:
+ return
+
+ data = hits.get('hits')
+
+ if data is None:
+ return
+
+ for result in data:
+ if result is None:
+ continue
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(result), self.__name__, event)
+ self.notifyListeners(evt)
+
+ content = result.get('content')
+
+ if content is None:
+ continue
+
+ snippet = content.get('snippet')
+
+ if snippet is None:
+ continue
+
+ links = self.sf.extractUrlsFromText(snippet.replace('', '').replace(' ', ''))
+ if links:
+ for link in links:
+ if link in self.results:
+ continue
+
+ host = self.sf.urlFQDN(link)
+
+ if not self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ continue
+
+ hosts.append(host)
+
+ if not self.getTarget().matches(self.sf.urlFQDN(link), includeChildren=True, includeParents=True):
+ self.debug("Skipped unrelated link: " + link)
+ continue
+
+ self.debug('Found a link: ' + link)
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', link, self.__name__, event)
+ self.notifyListeners(evt)
+ self.results[link] = True
+
+ emails = SpiderFootHelpers.extractEmailsFromText(snippet.replace('', '').replace(' ', ''))
+ if emails:
+ for email in emails:
+ if email in self.results:
+ continue
+
+ mail_domain = email.lower().split('@')[1]
+ if not self.getTarget().matches(mail_domain, includeChildren=True, includeParents=True):
+ self.debug("Skipped unrelated email address: " + email)
+ continue
+
+ self.info("Found e-mail address: " + email)
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+ self.results[email] = True
+
+ for host in set(hosts):
+ if self.checkForStop():
+ return
+
+ if self.errorState:
+ return
+
+ if self.opts['dns_resolve'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ evt = SpiderFootEvent("INTERNET_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+ if self.sf.isDomain(host, self.opts["_internettlds"]):
+ evt = SpiderFootEvent("DOMAIN_NAME", host, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_grep_app class
diff --git a/spiderfoot/modules/sfp_greynoise.py b/spiderfoot/modules/sfp_greynoise.py
new file mode 100644
index 0000000000000000000000000000000000000000..661838ffdd8d47c4d462981df0e91a518f1216ea
--- /dev/null
+++ b/spiderfoot/modules/sfp_greynoise.py
@@ -0,0 +1,303 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_greynoise
+# Purpose: Query GreyNoise's API
+#
+# Author: Steve Micallef
+# Updated By: Brad Chiappetta, GreyNoise
+#
+# Created: 20/11/2018
+# Updated: 31-Aug-2022
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+from datetime import datetime
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_greynoise(SpiderFootPlugin):
+
+ meta = {
+ "name": "GreyNoise",
+ "summary": "Obtain IP enrichment data from GreyNoise",
+ "flags": ["apikey"],
+ "useCases": ["Investigate", "Passive"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://greynoise.io/",
+ "model": "FREE_AUTH_LIMITED",
+ "references": ["https://docs.greynoise.io/", "https://viz.greynoise.io/signup"],
+ "apiKeyInstructions": [
+ "Visit https://viz.greynoise.io/signup",
+ "Sign up for a free account",
+ "Navigate to https://viz.greynoise.io/account",
+ "The API key is listed under 'API Key'",
+ ],
+ "favIcon": "https://viz.greynoise.io/favicon.ico",
+ "logo": "https://viz.greynoise.io/_nuxt/img/greynoise-logo.dccd59d.png",
+ "description": "At GreyNoise, we collect and analyze untargeted, widespread, "
+ "and opportunistic scan and attack activity that reaches every server directly connected to the Internet. "
+ "Mass scanners (such as Shodan and Censys), search engines, bots, worms, "
+ "and crawlers generate logs and events omnidirectionally on every IP address in the IPv4 space. "
+ "GreyNoise gives you the ability to filter this useless noise out.",
+ },
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "age_limit_days": 30,
+ "netblocklookup": True,
+ "maxnetblock": 24,
+ "subnetlookup": True,
+ "maxsubnet": 24
+ # 'asnlookup': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "GreyNoise API Key.",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ "netblocklookup": "Look up netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ "maxnetblock": "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ "subnetlookup": "Look up subnets which your target is a part of for blacklisting?",
+ "maxsubnet": "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
+ # 'asnlookup': "Look up ASNs that your target is a member of?"
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "NETBLOCK_MEMBER", "NETBLOCK_OWNER"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_ASN",
+ "MALICIOUS_SUBNET",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "COMPANY_NAME",
+ "GEOINFO",
+ "BGP_AS_MEMBER",
+ "OPERATING_SYSTEM",
+ "RAW_RIR_DATA",
+ ]
+
+ def queryIP(self, qry, qry_type):
+ gn_context_url = "https://api.greynoise.io/v2/noise/context/"
+ gn_gnql_url = "https://api.greynoise.io/v2/experimental/gnql?query="
+
+ headers = {"key": self.opts["api_key"]}
+ res = {}
+ if qry_type == "ip":
+ self.debug(f"Querying GreyNoise for IP: {qry}")
+ res = {}
+ ip_response = self.sf.fetchUrl(
+ gn_context_url + qry,
+ timeout=self.opts["_fetchtimeout"],
+ useragent="greynoise-spiderfoot-v1.2.0",
+ headers=headers,
+ )
+ if ip_response["code"] == "200":
+ res = json.loads(ip_response["content"])
+ else:
+ self.debug(f"Querying GreyNoise for Netblock: {qry}")
+ query_response = self.sf.fetchUrl(
+ gn_gnql_url + qry,
+ timeout=self.opts["_fetchtimeout"],
+ useragent="greynoise-spiderfoot-v1.1.0",
+ headers=headers,
+ )
+ if query_response["code"] == "200":
+ res = json.loads(query_response["content"])
+
+ if not res:
+ self.error("Greynoise API key seems to have been rejected or you have exceeded usage limits.")
+ self.errorState = True
+ return None
+
+ return res
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error("You enabled sfp_greynoise but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "NETBLOCK_OWNER":
+ if not self.opts["netblocklookup"]:
+ return
+
+ max_netblock = self.opts['maxnetblock']
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ if eventName == "NETBLOCK_MEMBER":
+ if not self.opts["subnetlookup"]:
+ return
+
+ max_subnet = self.opts['maxsubnet']
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ if eventName == "IP_ADDRESS":
+ evtType = "MALICIOUS_IPADDR"
+ qryType = "ip"
+ if eventName.startswith("NETBLOCK_"):
+ evtType = "MALICIOUS_IPADDR"
+ qryType = "netblock"
+ if eventName == "AFFILIATE_IPADDR":
+ evtType = "MALICIOUS_AFFILIATE_IPADDR"
+ qryType = "ip"
+
+ ret = self.queryIP(eventData, qryType)
+
+ if not ret:
+ return
+
+ if "data" not in ret and "seen" not in ret:
+ return
+
+ if "data" in ret and len(ret["data"]) > 0:
+ for rec in ret["data"]:
+ if rec.get("seen", None):
+ self.debug(f"Found threat info in Greynoise: {rec['ip']}")
+ lastseen = rec.get("last_seen", "1970-01-01")
+ lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d")
+ lastseen_ts = int(time.mktime(lastseen_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"])
+ if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts:
+ self.debug(f"Record [{rec['ip']}] found but too old, skipping.")
+ return
+
+ # Only report meta data about the target, not affiliates
+ if rec.get("metadata") and eventName == "IP_ADDRESS":
+ met = rec.get("metadata")
+ if met.get("country", "unknown") != "unknown":
+ loc = ""
+ if met.get("city"):
+ loc = met.get("city") + ", "
+ loc += met.get("country")
+ e = SpiderFootEvent("GEOINFO", loc, self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("asn", "unknown") != "unknown":
+ asn = met.get("asn").replace("AS", "")
+ e = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("organization", "unknown") != "unknown":
+ e = SpiderFootEvent("COMPANY_NAME", met.get("organization"), self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("os", "unknown") != "unknown":
+ e = SpiderFootEvent("OPERATING_SYSTEM", met.get("os"), self.__name__, event)
+ self.notifyListeners(e)
+ e = SpiderFootEvent("RAW_RIR_DATA", str(rec), self.__name__, event)
+ self.notifyListeners(e)
+
+ if rec.get("classification"):
+ descr = (
+ "GreyNoise - Mass-Scanning IP Detected ["
+ + rec.get("ip")
+ + "]\n - Classification: "
+ + rec.get("classification")
+ )
+ if rec.get("tags"):
+ descr += "\n - " + "Scans For Tags: " + ", ".join(rec.get("tags"))
+ if rec.get("cve"):
+ descr += "\n - " + "Scans For CVEs: " + ", ".join(rec.get("cve"))
+ if rec.get("raw_data") and not (rec.get("tags") or ret.get("cve")):
+ descr += "\n - " + "Raw data: " + str(rec.get("raw_data"))
+ descr += "\nhttps://viz.greynoise.io/ip/" + rec.get("ip") + " "
+ e = SpiderFootEvent(evtType, descr, self.__name__, event)
+ self.notifyListeners(e)
+
+ if "seen" in ret:
+ if ret.get("seen", None):
+ lastseen = ret.get("last_seen", "1970-01-01")
+ lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d")
+ lastseen_ts = int(time.mktime(lastseen_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"])
+ if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ return
+
+ # Only report meta data about the target, not affiliates
+ if ret.get("metadata") and eventName == "IP_ADDRESS":
+ met = ret.get("metadata")
+ if met.get("country", "unknown") != "unknown":
+ loc = ""
+ if met.get("city"):
+ loc = met.get("city") + ", "
+ loc += met.get("country")
+ e = SpiderFootEvent("GEOINFO", loc, self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("asn", "unknown") != "unknown":
+ asn = met.get("asn").replace("AS", "")
+ e = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("organization", "unknown") != "unknown":
+ e = SpiderFootEvent("COMPANY_NAME", met.get("organization"), self.__name__, event)
+ self.notifyListeners(e)
+ if met.get("os", "unknown") != "unknown":
+ e = SpiderFootEvent("OPERATING_SYSTEM", met.get("os"), self.__name__, event)
+ self.notifyListeners(e)
+ e = SpiderFootEvent("RAW_RIR_DATA", str(ret), self.__name__, event)
+ self.notifyListeners(e)
+
+ if ret.get("classification"):
+ descr = (
+ "GreyNoise - Mass-Scanning IP Detected ["
+ + eventData
+ + "]\n - Classification: "
+ + ret.get("classification")
+ )
+ if ret.get("tags"):
+ descr += "\n - " + "Scans For Tags: " + ", ".join(ret.get("tags"))
+ if ret.get("cve"):
+ descr += "\n - " + "Scans For CVEs: " + ", ".join(ret.get("cve"))
+ if ret.get("raw_data") and not (ret.get("tags") or ret.get("cve")):
+ descr += "\n - " + "Raw data: " + str(ret.get("raw_data"))
+ descr += "\nhttps://viz.greynoise.io/ip/" + ret.get("ip") + " "
+ e = SpiderFootEvent(evtType, descr, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_greynoise class
diff --git a/spiderfoot/modules/sfp_greynoise_community.py b/spiderfoot/modules/sfp_greynoise_community.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d88a8bbc0cf6a91cc8b4295bc8fb32634885fdb
--- /dev/null
+++ b/spiderfoot/modules/sfp_greynoise_community.py
@@ -0,0 +1,180 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_greynoise_community
+# Purpose: Query GreyNoise's Community API
+#
+# Author: Brad Chiappetta, GreyNoise
+# Updated By: Brad Chiappetta, GreyNoise
+#
+# Created: 31-Aug-2022
+# Updated: 31-Aug-2022
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+from datetime import datetime
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_greynoise_community(SpiderFootPlugin):
+
+ meta = {
+ "name": "GreyNoise Community",
+ "summary": "Obtain IP enrichment data from GreyNoise Community API",
+ "flags": ["apikey"],
+ "useCases": ["Investigate", "Passive"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://greynoise.io/",
+ "model": "FREE_AUTH_LIMITED",
+ "references": ["https://docs.greynoise.io/reference/get_v3-community-ip", "https://viz.greynoise.io/signup"],
+ "apiKeyInstructions": [
+ "Visit https://viz.greynoise.io/signup",
+ "Sign up for a free account",
+ "Navigate to https://viz.greynoise.io/account/",
+ "The API key is listed under 'API Key'",
+ ],
+ "favIcon": "https://viz.greynoise.io/favicon.ico",
+ "logo": "https://viz.greynoise.io/_nuxt/img/greynoise-logo.dccd59d.png",
+ "description": "At GreyNoise, we collect and analyze untargeted, widespread, "
+ "and opportunistic scan and attack activity that reaches every server directly connected to the Internet. "
+ "Mass scanners (such as Shodan and Censys), search engines, bots, worms, "
+ "and crawlers generate logs and events omnidirectionally on every IP address in the IPv4 space. "
+ "GreyNoise gives you the ability to filter this useless noise out.",
+ },
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "age_limit_days": 30,
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "GreyNoise Community API Key.",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "NETBLOCK_MEMBER", "NETBLOCK_OWNER"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "MALICIOUS_IPADDR",
+ "COMPANY_NAME",
+ "RAW_RIR_DATA",
+ ]
+
+ def queryIP(self, qry, qry_type):
+ gn_community_url = "https://api.greynoise.io/v3/community/"
+
+ headers = {"key": self.opts["api_key"]}
+ res = {}
+ if qry_type == "ip":
+ self.debug(f"Querying GreyNoise Community API for IP: {qry}")
+ ip_res = {}
+ ip_response = self.sf.fetchUrl(
+ gn_community_url + qry,
+ timeout=self.opts["_fetchtimeout"],
+ useragent="greynoise-spiderfoot-community-v1.2.0",
+ headers=headers,
+ )
+ if ip_response["code"] == "200":
+ ip_res = json.loads(ip_response["content"])
+ res = ip_res
+
+ if not res:
+ self.error("Greynoise API key seems to have been rejected or you have exceeded usage limits.")
+ self.errorState = True
+ return None
+
+ return res
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error("You enabled sfp_greynoise_community but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "IP_ADDRESS":
+ evtType = "MALICIOUS_IPADDR"
+ qryType = "ip"
+ if eventName == "AFFILIATE_IPADDR":
+ evtType = "MALICIOUS_AFFILIATE_IPADDR"
+ qryType = "ip"
+
+ ret = self.queryIP(eventData, qryType)
+
+ if not ret:
+ return
+
+ if "data" not in ret and "noise" not in ret:
+ return
+
+ if "noise" in ret:
+ if ret.get("noise", None):
+ lastseen = ret.get("last_seen", "1970-01-01")
+ lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d")
+ lastseen_ts = int(time.mktime(lastseen_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"])
+ if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ return
+ e = SpiderFootEvent("RAW_RIR_DATA", str(ret), self.__name__, event)
+ self.notifyListeners(e)
+
+ # Only report meta data about the target, not affiliates
+ if ret.get("name", "unknown") != "unknown":
+ e = SpiderFootEvent("COMPANY_NAME", ret.get("name"), self.__name__, event)
+ self.notifyListeners(e)
+
+ if ret.get("classification"):
+ descr = (
+ "GreyNoise - Mass-Scanning IP Detected ["
+ + eventData
+ + "]\n - Classification: "
+ + ret.get("classification")
+ )
+ descr += "\nhttps://viz.greynoise.io/ip/" + ret.get("ip") + " "
+ e = SpiderFootEvent(evtType, descr, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_greynoise_community class
diff --git a/spiderfoot/modules/sfp_h1nobbdde.py b/spiderfoot/modules/sfp_h1nobbdde.py
new file mode 100644
index 0000000000000000000000000000000000000000..511463c7d190aeaa8124cd0cf07770bddf282bea
--- /dev/null
+++ b/spiderfoot/modules/sfp_h1nobbdde.py
@@ -0,0 +1,112 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_h1.nobbd.de
+# Purpose: Query the the unofficial HackerOne disclosure timeline database
+# to see if our target appears.
+#
+# Author: Dhiraj Mishra
+# Created: 28/10/2018
+# Copyright: (c) Dhiraj Mishra
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_h1nobbdde(SpiderFootPlugin):
+
+ meta = {
+ 'name': "HackerOne (Unofficial)",
+ 'summary': "Check external vulnerability scanning/reporting service h1.nobbd.de to see if the target is listed.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "http://www.nobbd.de/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "http://www.nobbd.de/index.php#projekte",
+ "https://twitter.com/disclosedh1"
+ ],
+ 'favIcon': "http://www.nobbd.de/favicon.ico",
+ 'logo': "http://www.nobbd.de/favicon.ico",
+ 'description': "Unofficial Bug Monitoring platform for HackerOne.",
+ }
+ }
+
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["VULNERABILITY_DISCLOSURE"]
+
+ # Query h1.nobbd.de
+ def queryOBB(self, qry):
+ ret = list()
+ url = "http://h1.nobbd.de/search.php?q=" + qry
+ res = self.sf.fetchUrl(url, timeout=30, useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.debug("No content returned from h1.nobbd.de")
+ return None
+
+ try:
+ rx = re.compile("" + m[0] + " ")
+ except Exception as e:
+ self.error(f"Error processing response from h1.nobbd.de: {e}")
+ return None
+
+ return ret
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ data = list()
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ obb = self.queryOBB(eventData)
+ if obb:
+ data.extend(obb)
+
+ for n in data:
+ e = SpiderFootEvent("VULNERABILITY_DISCLOSURE", n, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_h1nobbdde class
diff --git a/spiderfoot/modules/sfp_hackertarget.py b/spiderfoot/modules/sfp_hackertarget.py
new file mode 100644
index 0000000000000000000000000000000000000000..46d5cf60e40d0aa489ae8355f56aa46f88fd002b
--- /dev/null
+++ b/spiderfoot/modules/sfp_hackertarget.py
@@ -0,0 +1,366 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_hackertarget
+# Purpose: SpiderFoot plug-in to search HackerTarget.com for hosts sharing
+# the same IP. Optionally, also perform a basic TCP/UDP port scan
+# for commonly open ports using HackerTarget.com port scan tools.
+#
+# Author: Steve Micallef
+#
+# Created: 12/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_hackertarget(SpiderFootPlugin):
+
+ meta = {
+ 'name': "HackerTarget",
+ 'summary': "Search HackerTarget.com for hosts sharing the same IP.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://hackertarget.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://hackertarget.com/research/",
+ "https://hackertarget.com/category/tools/"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://hackertarget.com/",
+ 'logo': "https://hackertarget.com/wp-content/uploads/2018/03/online-security.png",
+ 'description': "Simplify the security assessment process with hosted vulnerability scanners. "
+ "From attack surface discovery to vulnerability identification, "
+ "actionable network intelligence for IT & security operations. "
+ "Proactively hunt for security weakness. "
+ "Pivot from attack surface discovery to vulnerability identification.",
+ }
+ }
+
+ opts = {
+ 'cohostsamedomain': False,
+ 'verify': True,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxcohost': 100,
+ 'http_headers': False,
+ }
+
+ optdescs = {
+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",
+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ 'http_headers': "Retrieve IP HTTP headers using HackerTarget.com",
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "NETBLOCK_OWNER",
+ 'DOMAIN_NAME_PARENT'
+ ]
+
+ def producedEvents(self):
+ return [
+ "CO_HOSTED_SITE",
+ "IP_ADDRESS",
+ 'WEBSERVER_HTTPHEADERS',
+ 'RAW_DNS_RECORDS',
+ 'INTERNET_NAME',
+ 'INTERNET_NAME_UNRESOLVED',
+ 'DOMAIN_NAME',
+ 'AFFILIATE_DOMAIN_NAME',
+ 'AFFILIATE_INTERNET_NAME',
+ 'AFFILIATE_INTERNET_NAME_UNRESOLVED'
+ ]
+
+ def httpHeaders(self, ip):
+ """Retrieve HTTP headers for IP address
+
+ Args:
+ ip (str): IPv4 address
+
+ Returns:
+ dict: HTTP headers
+ """
+ params = urllib.parse.urlencode({
+ 'q': ip
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.hackertarget.com/httpheaders/?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch HTTP headers for {ip} from HackerTarget.com.")
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by HackerTarget")
+ self.errorState = True
+ return None
+
+ if not res['content'].startswith('HTTP/'):
+ self.debug(f"Found no HTTP headers for {ip}")
+ return None
+
+ headers = dict()
+
+ for header in res['content'].splitlines():
+ if ': ' not in header:
+ continue
+ k = header.split(': ')[0].lower()
+ v = ': '.join(header.split(': ')[1:])
+ headers[k] = v
+
+ return headers
+
+ def zoneTransfer(self, ip):
+ """Retrieve DNS zone transfer
+
+ Args:
+ ip (str): IPv4 address
+
+ Returns:
+ list: DNS zone
+ """
+ params = urllib.parse.urlencode({
+ 'q': ip
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.hackertarget.com/zonetransfer/?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ if res['content'] is None:
+ self.error(f"Unable to fetch DNS zone for {ip} from HackerTarget.com.")
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by HackerTarget")
+ self.errorState = True
+ return None
+
+ records = list()
+
+ for record in res['content'].splitlines():
+ if record.strip().startswith(';'):
+ continue
+ if record.strip() == '':
+ continue
+ records.append(record.strip())
+
+ return records
+
+ def reverseIpLookup(self, ip):
+ """Reverse lookup hosts on the same IP address
+
+ Args:
+ ip (str): IPv4 address
+
+ Returns:
+ list: (co)hosts on provided IP addresses
+ """
+ params = urllib.parse.urlencode({
+ 'q': ip
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.hackertarget.com/reverseiplookup/?{params}",
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ if res['content'] is None:
+ self.error("Unable to fetch hackertarget.com content.")
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by HackerTarget")
+ self.errorState = True
+ return None
+
+ if "No records" in res['content']:
+ return None
+
+ hosts = res['content'].split('\n')
+
+ self.debug(f"Found {len(hosts)} on {ip}")
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ self.currentEventSrc = event
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if srcModuleName == "sfp_hackertarget" and eventName == "IP_ADDRESS":
+ self.debug(f"Ignoring {eventName}, from self.")
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if eventName == 'NETBLOCK_OWNER':
+ if not self.opts['netblocklookup']:
+ return
+
+ max_netblock = self.opts['maxnetblock']
+ net_size = IPNetwork(eventData).prefixlen
+ if net_size < max_netblock:
+ self.debug(f"Network size bigger than permitted: {net_size} > {max_netblock}")
+ return
+
+ if eventName == 'DOMAIN_NAME_PARENT':
+ records = self.zoneTransfer(eventData)
+
+ if not records:
+ return
+
+ evt = SpiderFootEvent('RAW_DNS_RECORDS', "\n".join(records), self.__name__, event)
+ self.notifyListeners(evt)
+
+ # Try and pull out individual records
+ for row in records:
+ pat = re.compile(r"^(\S+)\.?\s+\d+\s+IN\s+[AC].*", re.IGNORECASE | re.DOTALL)
+ grps = re.findall(pat, row)
+
+ if len(grps) == 0:
+ continue
+
+ hosts = list()
+
+ for strdata in grps:
+ self.debug("Matched: " + strdata)
+ if strdata.endswith("."):
+ hosts.append(strdata[:-1])
+ else:
+ hosts.append(strdata)
+
+ for host in set(hosts):
+ if self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ evt_type = 'INTERNET_NAME'
+ else:
+ evt_type = 'AFFILIATE_INTERNET_NAME'
+
+ if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):
+ self.debug(f"Host {host} could not be resolved")
+ evt_type += '_UNRESOLVED'
+
+ evt = SpiderFootEvent(evt_type, host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(host, self.opts['_internettlds']):
+ if evt_type.startswith('AFFILIATE'):
+ evt = SpiderFootEvent('AFFILIATE_DOMAIN_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent('DOMAIN_NAME', host, self.__name__, event)
+ self.notifyListeners(evt)
+
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ if str(ipaddr) not in self.results:
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+ self.results[eventData] = True
+
+ myres = list()
+
+ for ip in qrylist:
+ if self.checkForStop():
+ return
+
+ hosts = self.reverseIpLookup(ip)
+ if not hosts:
+ continue
+
+ for h in hosts:
+ if " " in h:
+ continue
+
+ self.info(f"Found something on same IP: {h}")
+
+ if not self.opts['cohostsamedomain']:
+ if self.getTarget().matches(h, includeParents=True):
+ self.debug(f"Skipping {h} because it is on the same domain.")
+ continue
+
+ if h not in myres and h != ip:
+ if self.opts['verify'] and not self.sf.validateIP(h, ip):
+ self.debug(f"Host {h} no longer resolves to {ip}")
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ # Create an IP Address event stemming from the netblock as the
+ # link to the co-host.
+ if eventName == "NETBLOCK_OWNER":
+ ipe = SpiderFootEvent("IP_ADDRESS", ip, self.__name__, event)
+ self.notifyListeners(ipe)
+ evt = SpiderFootEvent("CO_HOSTED_SITE", h.lower(), self.__name__, ipe)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("CO_HOSTED_SITE", h.lower(), self.__name__, event)
+ self.notifyListeners(evt)
+
+ myres.append(h.lower())
+ self.cohostcount += 1
+
+ # For netblocks, we need to create the IP address event so that
+ # the threat intel event is more meaningful.
+ if eventName == 'NETBLOCK_OWNER':
+ pevent = SpiderFootEvent("IP_ADDRESS", ip, self.__name__, event)
+ self.notifyListeners(pevent)
+ else:
+ pevent = event
+
+ if self.opts.get('http_headers', True):
+ http_headers = self.httpHeaders(ip)
+ if http_headers is not None:
+ e = SpiderFootEvent('WEBSERVER_HTTPHEADERS', json.dumps(http_headers), self.__name__, pevent)
+ e.actualSource = ip
+ self.notifyListeners(e)
+
+# End of sfp_hackertarget class
diff --git a/spiderfoot/modules/sfp_hashes.py b/spiderfoot/modules/sfp_hashes.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4947b66723ef82419dda6fc467180ae0bcfcc16
--- /dev/null
+++ b/spiderfoot/modules/sfp_hashes.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_hashes
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying hashes
+#
+# Author: Steve Micallef
+#
+# Created: 24/01/2020
+# Copyright: (c) Steve Micallef 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_hashes(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Hash Extractor",
+ 'summary': "Identify MD5 and SHA hashes in web content, files and more.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ # options specific to this module
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT", "BASE64_DATA",
+ "LEAKSITE_CONTENT", "RAW_DNS_RECORDS",
+ "RAW_FILE_META_DATA"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["HASH"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ hashes = SpiderFootHelpers.extractHashesFromText(eventData)
+ for hashtup in hashes:
+ hashalgo, hashval = hashtup
+
+ evt = SpiderFootEvent("HASH", f"[{hashalgo}] {hashval}", self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+# End of sfp_hashes class
diff --git a/spiderfoot/modules/sfp_haveibeenpwned.py b/spiderfoot/modules/sfp_haveibeenpwned.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f35dddd73de65b75216bd240feccc58dcd41b8b
--- /dev/null
+++ b/spiderfoot/modules/sfp_haveibeenpwned.py
@@ -0,0 +1,253 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_haveibeenpwned
+# Purpose: Query haveibeenpwned.com to see if an e-mail account has been hacked.
+#
+# Author: Steve Micallef
+#
+# Created: 19/02/2015
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_haveibeenpwned(SpiderFootPlugin):
+
+ meta = {
+ 'name': "HaveIBeenPwned",
+ 'summary': "Check HaveIBeenPwned.com for hacked e-mail addresses identified in breaches.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "https://haveibeenpwned.com/",
+ 'model': "COMMERCIAL_ONLY",
+ 'references': [
+ "https://haveibeenpwned.com/API/v3",
+ "https://haveibeenpwned.com/FAQs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://haveibeenpwned.com/API/Key",
+ "Register an account",
+ "Visit https://haveibeenpwned.com/API/Key",
+ ],
+ 'favIcon': "https://haveibeenpwned.com/favicon.ico",
+ 'logo': "https://haveibeenpwned.com/favicon.ico",
+ 'description': "Check if you have an account that has been compromised in a data breach.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": ""
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "HaveIBeenPwned.com API key."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["EMAILADDR", "PHONE_NUMBER"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["EMAILADDR_COMPROMISED", "PHONE_NUMBER_COMPROMISED", "LEAKSITE_CONTENT", "LEAKSITE_URL"]
+
+ def query(self, qry):
+ if self.opts['api_key']:
+ version = "3"
+ else:
+ version = "2"
+
+ url = f"https://haveibeenpwned.com/api/v{version}/breachedaccount/{qry}"
+ hdrs = {"Accept": f"application/vnd.haveibeenpwned.v{version}+json"}
+ retry = 0
+
+ if self.opts['api_key']:
+ hdrs['hibp-api-key'] = self.opts['api_key']
+
+ while retry < 2:
+ # https://haveibeenpwned.com/API/v2#RateLimiting
+ time.sleep(1.5)
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot", headers=hdrs)
+
+ if res['code'] == "200":
+ break
+
+ if res['code'] == "404":
+ return None
+
+ if res['code'] == "429":
+ # Back off a little further
+ time.sleep(2)
+ retry += 1
+
+ if res['code'] == "401":
+ self.error("Failed to authenticate key with HaveIBeenPwned.com.")
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from HaveIBeenPwned?: {e}")
+
+ return None
+
+ def queryPaste(self, qry):
+ url = f"https://haveibeenpwned.com/api/v3/pasteaccount/{qry}"
+ headers = {
+ 'Accept': "application/json",
+ 'hibp-api-key': self.opts['api_key']
+ }
+
+ retry = 0
+
+ while retry < 2:
+ # https://haveibeenpwned.com/API/v2#RateLimiting
+ time.sleep(1.5)
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot", headers=headers)
+
+ if res['code'] == "200":
+ break
+
+ if res['code'] == "404":
+ return None
+
+ if res['code'] == "429":
+ # Back off a little further
+ time.sleep(2)
+ retry += 1
+
+ if res['code'] == "401":
+ self.error("Failed to authenticate key with HaveIBeenPwned.com.")
+ self.errorState = True
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from HaveIBeenPwned?: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_haveibeenpwned but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+ if data is not None:
+ for n in data:
+ try:
+ site = n["Name"]
+ except Exception as e:
+ self.debug(f"Unable to parse result from HaveIBeenPwned?: {e}")
+ continue
+
+ # Notify other modules of what you've found
+ if eventName == 'EMAILADDR':
+ e = SpiderFootEvent("EMAILADDR_COMPROMISED", eventData + " [" + site + "]",
+ self.__name__, event)
+ else:
+ e = SpiderFootEvent("PHONE_NUMBER_COMPROMISED", eventData + " [" + site + "]",
+ self.__name__, event)
+ self.notifyListeners(e)
+
+ # This API endpoint doesn't support phone numbers
+ if eventName == "PHONE_NUMBER":
+ return
+ pasteData = self.queryPaste(eventData)
+ if pasteData is None:
+ return
+
+ sites = {
+ "Pastebin": "https://pastebin.com/",
+ "Pastie": "http://pastie.org/p/",
+ "Slexy": "https://slexy.org/view/",
+ "Ghostbin": "https://ghostbin.com/paste/",
+ "JustPaste": "https://justpaste.it/",
+ }
+ links = set()
+ for n in pasteData:
+ try:
+ source = n.get("Source")
+ site = source
+ if source in sites:
+ site = f"{sites[n.get('Source')]}{n.get('Id')}"
+ links.add(site)
+
+ except Exception as e:
+ self.debug(f"Unable to parse result from HaveIBeenPwned?: {e}")
+ continue
+
+ for link in links:
+ try:
+ self.debug("Found a link: " + link)
+
+ if self.checkForStop():
+ return
+
+ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.debug(f"Ignoring {link} as no data returned")
+ continue
+
+ if re.search(r"[^a-zA-Z\-\_0-9]" + re.escape(eventData) + r"[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:
+ continue
+
+ evt1 = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)
+ self.notifyListeners(evt1)
+
+ evt2 = SpiderFootEvent("LEAKSITE_CONTENT", res['content'], self.__name__, evt1)
+ self.notifyListeners(evt2)
+
+ except Exception as e:
+ self.debug(f"Unable to parse result from HaveIBeenPwned?: {e}")
+ continue
+
+# End of sfp_haveibeenpwned class
diff --git a/spiderfoot/modules/sfp_honeypot.py b/spiderfoot/modules/sfp_honeypot.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cc81e332d0153515e70bfc53165af36c69f36fa
--- /dev/null
+++ b/spiderfoot/modules/sfp_honeypot.py
@@ -0,0 +1,232 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_honeypot
+# Purpose: SpiderFoot plug-in for looking up whether IPs appear in the
+# ProjectHoneyPot.org database.
+#
+# Author: Steve Micallef
+#
+# Created: 16/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_honeypot(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Project Honey Pot",
+ 'summary': "Query the Project Honey Pot database for IP addresses.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.projecthoneypot.org/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://www.projecthoneypot.org/httpbl_api.php",
+ "https://www.projecthoneypot.org/services_overview.php",
+ "https://www.projecthoneypot.org/faq.php"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.projecthoneypot.org",
+ "Sign up for a free account",
+ "Navigate to https://www.projecthoneypot.org/httpbl_configure.php'",
+ "Request for an API key",
+ "The API key is listed under 'Your http:BL Access Key'"
+ ],
+ 'favIcon': "https://www.projecthoneypot.org/favicon.ico",
+ 'logo': "https://www.projecthoneypot.org/images/php_logo.gif",
+ 'description': "Project Honey Pot is the first and only distributed system for identifying spammers "
+ "and the spambots they use to scrape addresses from your website. "
+ "Using the Project Honey Pot system you can install addresses "
+ "that are custom-tagged to the time and IP address of a visitor to your site. "
+ "If one of these addresses begins receiving email we not only can tell that the messages are spam, "
+ "but also the exact moment when the address was harvested and the IP address that gathered it.",
+ }
+ }
+
+ opts = {
+ 'api_key': "",
+ 'searchengine': False,
+ 'threatscore': 0,
+ 'timelimit': 30,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'subnetlookup': True,
+ 'maxsubnet': 24
+ }
+
+ optdescs = {
+ 'api_key': "ProjectHoneyPot.org API key.",
+ 'searchengine': "Include entries considered search engines?",
+ 'threatscore': "Threat score minimum, 0 being everything and 255 being only the most serious.",
+ 'timelimit': "Maximum days old an entry can be. 255 is the maximum, 0 means you'll get nothing.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
+ }
+
+ results = None
+ errorState = False
+
+ # Status codes according to:
+ # http://www.projecthoneypot.org/httpbl_api.php
+ statuses = {
+ "0": "Search Engine",
+ "1": "Suspicious",
+ "2": "Harvester",
+ "3": "Suspicious & Harvester",
+ "4": "Comment Spammer",
+ "5": "Suspicious & Comment Spammer",
+ "6": "Harvester & Comment Spammer",
+ "7": "Suspicious & Harvester & Comment Spammer",
+ "8": "Unknown (8)",
+ "9": "Unknown (9)",
+ "10": "Unknown (10)"
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "NETBLOCK_OWNER",
+ "NETBLOCK_MEMBER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_NETBLOCK",
+ "BLACKLISTED_SUBNET",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ ]
+
+ # Swap 1.2.3.4 to 4.3.2.1
+ def reverseAddr(self, ipaddr):
+ return '.'.join(reversed(ipaddr.split('.')))
+
+ # Returns text about the IP status returned from DNS
+ def parseDNS(self, addr):
+ bits = addr.split(".")
+ if int(bits[1]) > self.opts['timelimit']:
+ return None
+
+ if int(bits[2]) < self.opts['threatscore']:
+ return None
+
+ if int(bits[3]) == 0 and self.opts['searchengine']:
+ return None
+
+ return f"{self.statuses[bits[3]]}\nLast Activity: {bits[1]} days ago\nThreat Level: {bits[2]}"
+
+ def queryAddr(self, qaddr, parentEvent):
+ eventName = parentEvent.eventType
+
+ text = None
+ try:
+ lookup = f"{self.opts['api_key']}.{self.reverseAddr(qaddr)}.dnsbl.httpbl.org"
+
+ self.debug(f"Checking ProjectHoneyPot: {lookup}")
+ addrs = self.sf.resolveHost(lookup)
+ if not addrs:
+ return
+
+ self.debug(f"Addresses returned: {addrs}")
+
+ for addr in addrs:
+ text = self.parseDNS(addr)
+ if text is not None:
+ break
+ except Exception as e:
+ self.debug(f"ProjectHoneyPot did not resolve {qaddr} / {lookup}: {e}")
+
+ if not text:
+ return
+
+ if eventName == "AFFILIATE_IPADDR":
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == "IP_ADDRESS":
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == "NETBLOCK_OWNER":
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == "NETBLOCK_MEMBER":
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ url = f"https://www.projecthoneypot.org/ip_{qaddr}"
+
+ evt = SpiderFootEvent(malicious_type, f"ProjectHoneyPot ({qaddr}): {text}\n{url} ", self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, f"ProjectHoneyPot ({qaddr}): {text}\n{url} ", self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if not self.opts['api_key']:
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'NETBLOCK_OWNER':
+ if not self.opts['netblocklookup']:
+ return
+
+ max_netblock = self.opts['maxnetblock']
+ if IPNetwork(eventData).prefixlen < max_netblock:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")
+ return
+
+ if eventName == 'NETBLOCK_MEMBER':
+ if not self.opts['subnetlookup']:
+ return
+
+ max_subnet = self.opts['maxsubnet']
+ if IPNetwork(eventData).prefixlen < max_subnet:
+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")
+ return
+
+ if eventName.startswith("NETBLOCK_"):
+ for addr in IPNetwork(eventData):
+ if self.checkForStop():
+ return
+ self.queryAddr(str(addr), event)
+ else:
+ self.queryAddr(eventData, event)
+
+# End of sfp_honeypot class
diff --git a/spiderfoot/modules/sfp_hosting.py b/spiderfoot/modules/sfp_hosting.py
new file mode 100644
index 0000000000000000000000000000000000000000..311c759767bf7fbf7c41b269679977ef79592728
--- /dev/null
+++ b/spiderfoot/modules/sfp_hosting.py
@@ -0,0 +1,108 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_hosting
+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains
+# appear in an IP categorization table of hosting providers.
+#
+# Author: Steve Micallef
+#
+# Created: 16/08/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_hosting(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Hosting Provider Identifier",
+ 'summary': "Find out if any IP addresses identified fall within known 3rd party hosting ranges, e.g. Amazon, Azure, etc.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ # Target
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.__dataSource__ = "DNS"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["PROVIDER_HOSTING"]
+
+ def queryAddr(self, qaddr):
+ data = dict()
+ url = "https://raw.githubusercontent.com/client9/ipcat/master/datacenters.csv"
+
+ data['content'] = self.sf.cacheGet("sfipcat", 48)
+ if data['content'] is None:
+ data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])
+
+ if data['content'] is None:
+ self.error("Unable to fetch " + url)
+ return None
+
+ self.sf.cachePut("sfipcat", data['content'])
+
+ for line in data['content'].split('\n'):
+ if "," not in line:
+ continue
+ try:
+ [start, end, title, url] = line.split(",")
+ except Exception:
+ continue
+
+ try:
+ if IPAddress(qaddr) > IPAddress(start) and IPAddress(qaddr) < IPAddress(end):
+ return [title, url]
+ except Exception as e:
+ self.debug("Encountered an issue processing an IP: " + str(e))
+ continue
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ ret = self.queryAddr(eventData)
+ if ret:
+ evt = SpiderFootEvent("PROVIDER_HOSTING", ret[0] + ": " + ret[1],
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_hosting class
diff --git a/spiderfoot/modules/sfp_hostio.py b/spiderfoot/modules/sfp_hostio.py
new file mode 100644
index 0000000000000000000000000000000000000000..916577255a54d811e37fed7e559281a552f34eb4
--- /dev/null
+++ b/spiderfoot/modules/sfp_hostio.py
@@ -0,0 +1,219 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_hostio
+# Purpose: Host.io database query module
+#
+# Author: Lev Trubach
+#
+# Created: 2020-08-21
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_hostio(SpiderFootPlugin):
+
+ meta = {
+ "name": "Host.io",
+ "summary": "Obtain information about domain names from host.io.",
+ 'flags': ["apikey"],
+ "useCases": ["Passive"],
+ "categories": ["Passive DNS"],
+ "dataSource": {
+ "website": "https://host.io",
+ "model": "FREE_AUTH_LIMITED",
+ "references": ["https://host.io/docs"],
+ "apiKeyInstructions": [
+ "Visit https://host.io/signup",
+ "Register a free account",
+ "Visit https://host.io/dashboard and use the authentication token provided",
+ ],
+ "favIcon": "https://host.io/static/images/hostio/favicon.png?v2",
+ "logo": "https://host.io/static/images/hostio/favicon.png?v2", # Seems like they embed it as SVG
+ "description": "We collect data on every known domain name, from every TLD, and update it every month. "
+ "Our data includes DNS records and website data for each of the domains."
+ "We process terabytes of data and summarize it to produce our final results. "
+ "Browse through our site to see backlinks, redirects, server details or IP address "
+ "and hosting provider details courtesy of IPinfo.io.",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ }
+
+ optdescs = {
+ "api_key": "Host.io API Key.",
+ }
+
+ errorState = False
+
+ def setup(self, sfc, userOpts=None):
+ if userOpts is None:
+ userOpts = {}
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ ]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "RAW_RIR_DATA",
+ "EMAILADDR",
+ "WEB_ANALYTICS_ID",
+ "WEBSERVER_TECHNOLOGY",
+ "PHYSICAL_COORDINATES",
+ "DESCRIPTION_ABSTRACT",
+ "GEOINFO",
+ ]
+
+ # When querying third parties, it's best to have a dedicated function
+ # to do so and avoid putting it in handleEvent()
+ def handle_error_response(self, qry, res):
+ try:
+ error_info = json.loads(res["content"])
+ except Exception:
+ error_info = None
+ if error_info:
+ error_message = error_info.get("error")
+ else:
+ error_message = None
+ if error_message:
+ error_str = f", message {error_message}"
+ else:
+ error_str = ""
+ self.info(f"Failed to get results for {qry}, code {res['code']}{error_str}")
+
+ def query(self, qry):
+ res = self.sf.fetchUrl(
+ f"https://host.io/api/full/{qry}",
+ headers={"Authorization": f"Bearer {self.opts['api_key']}"},
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+ if res["code"] != "200":
+ self.handle_error_response(qry, res)
+ return None
+
+ if res["content"] is None:
+ self.info(f"No Host.io info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res["content"])
+ except Exception as e:
+ self.error(f"Error processing JSON response from Host.io: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData} as already mapped.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(event.data)
+ if not data:
+ self.error(f"No data received for {event.data}")
+ return
+
+ found = False
+ ipinfo = data.get("ipinfo")
+ if ipinfo and isinstance(ipinfo, dict):
+ for address, ip_data in data["ipinfo"].items():
+ # Not supporting co-hosted sites yet
+ if not self.sf.validIP(address):
+ continue
+ evt = SpiderFootEvent("IP_ADDRESS", address, self.__name__, event)
+ self.notifyListeners(evt)
+ found = True
+
+ loc = ip_data.get("loc")
+ if loc and isinstance(loc, str):
+ loc_evt = SpiderFootEvent(
+ "PHYSICAL_COORDINATES", loc, self.__name__, evt
+ )
+ self.notifyListeners(loc_evt)
+ found = True
+
+ geo_info = ', '.join(filter(None, (ip_data.get(k) for k in ("city", "region", "country"))))
+ if geo_info:
+ geo_info_evt = SpiderFootEvent(
+ "GEOINFO", geo_info, self.__name__, evt
+ )
+ self.notifyListeners(geo_info_evt)
+ found = True
+
+ related = data.get("related")
+ if related and isinstance(related, dict):
+ email_section = related.get("email")
+ if email_section and isinstance(email_section, list):
+ for email_data in email_section:
+ if isinstance(email_data, dict):
+ value = email_data["value"]
+ if value and isinstance(value, str):
+ for email in value.split(','):
+ email = email.strip('.')
+ evt = SpiderFootEvent(
+ "EMAILADDR", email, self.__name__, event
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ web = data.get("web")
+ if web and isinstance(web, dict):
+ server = web.get("server")
+ if server and isinstance(server, str):
+ evt = SpiderFootEvent(
+ "WEBSERVER_TECHNOLOGY", server, self.__name__, event
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ google_analytics = web.get("googleanalytics")
+ if google_analytics and isinstance(google_analytics, str):
+ evt = SpiderFootEvent(
+ "WEB_ANALYTICS_ID", google_analytics, self.__name__, event
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ title = web.get("title")
+ if title and isinstance(title, str):
+ evt = SpiderFootEvent(
+ "DESCRIPTION_ABSTRACT", title, self.__name__, event
+ )
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", json.dumps(data), self.__name__, event
+ )
+ self.notifyListeners(evt)
diff --git a/spiderfoot/modules/sfp_hunter.py b/spiderfoot/modules/sfp_hunter.py
new file mode 100644
index 0000000000000000000000000000000000000000..54dcf4f1dfbc7c7ac0640806b27f3e0915c0cd78
--- /dev/null
+++ b/spiderfoot/modules/sfp_hunter.py
@@ -0,0 +1,179 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_hunter
+# Purpose: Query hunter.io using their API.
+#
+# Author: Steve Micallef
+#
+# Created: 22/02/2017
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_hunter(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Hunter.io",
+ 'summary': "Check for e-mail addresses and names on hunter.io.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://hunter.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://hunter.io/api"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://hunter.io/",
+ "Sign up for a free account",
+ "Click on 'Account Settings'",
+ "Click on 'API'",
+ "The API key is listed under 'Your API Key'"
+ ],
+ 'favIcon': "https://hunter.io/assets/head/favicon-d5796c45076e78aa5cf22dd53c5a4a54155062224bac758a412f3a849f38690b.ico",
+ 'logo': "https://hunter.io/assets/head/touch-icon-iphone-fd9330e31552eeaa12b177489943de997551bfd991c4c44e8c3d572e78aea5f3.png",
+ 'description': "Hunter lets you find email addresses in seconds and connect with the people that matter for your business.\n"
+ "The Domain Search lists all the people working in a company with their name "
+ "and email address found on the web. With 100+ million email addresses indexed, "
+ "effective search filters and scoring, it's the most powerful email-finding tool ever created.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": ""
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "Hunter.io API key."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "INTERNET_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["EMAILADDR", "EMAILADDR_GENERIC", "RAW_RIR_DATA"]
+
+ def query(self, qry, offset=0, limit=10):
+ params = {
+ "domain": qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ "api_key": self.opts['api_key'],
+ "offset": str(offset),
+ "limit": str(limit)
+ }
+
+ url = f"https://api.hunter.io/v2/domain-search?{urllib.parse.urlencode(params)}"
+
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
+
+ if res['code'] == "404":
+ return None
+
+ if not res['content']:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from hunter.io: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_hunter but did not set an API key!")
+ self.errorState = True
+ return
+
+ data = self.query(eventData, 0, 10)
+ if not data:
+ return
+
+ if "data" not in data:
+ return
+
+ # Check if we have more results on further pages
+ if "meta" in data:
+ maxgoal = data['meta'].get('results', 10)
+ else:
+ maxgoal = 10
+
+ rescount = len(data['data'].get('emails', list()))
+
+ while rescount <= maxgoal:
+ for email in data['data'].get('emails', list()):
+ # Notify other modules of what you've found
+ em = email.get('value')
+ if not em:
+ continue
+ if em.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ e = SpiderFootEvent(evttype, em, self.__name__, event)
+ self.notifyListeners(e)
+
+ if 'first_name' in email and 'last_name' in email:
+ if email['first_name'] is not None and email['last_name'] is not None:
+ n = email['first_name'] + " " + email['last_name']
+ e = SpiderFootEvent("RAW_RIR_DATA", "Possible full name: " + n,
+ self.__name__, event)
+ self.notifyListeners(e)
+
+ if rescount >= maxgoal:
+ return
+
+ data = self.query(eventData, rescount, 10)
+ if data is None:
+ return
+ if "data" not in data:
+ return
+
+ rescount += len(data['data'].get('emails', list()))
+
+# End of sfp_hunter class
diff --git a/spiderfoot/modules/sfp_hybrid_analysis.py b/spiderfoot/modules/sfp_hybrid_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5bccfe4f6ba0ee17f008c6e5f34120b45d26780
--- /dev/null
+++ b/spiderfoot/modules/sfp_hybrid_analysis.py
@@ -0,0 +1,313 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_hybrid_analysis
+# Purpose: Search Hybrid Analysis for domains and URLs related to the target.
+#
+# Authors:
+#
+# Created: 2020-08-09
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_hybrid_analysis(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Hybrid Analysis",
+ 'summary': "Search Hybrid Analysis for domains and URLs related to the target.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.hybrid-analysis.com",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://www.hybrid-analysis.com/knowledge-base",
+ "https://www.hybrid-analysis.com/docs/api/v2"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.hybrid-analysis.com/signup",
+ "Register a free account",
+ "Navigate to https://www.hybrid-analysis.com/my-account?tab=%23api-key-tab",
+ "Create an API Key",
+ "The API key is listed under 'API Key'"
+ ],
+ 'favIcon': "https://www.hybrid-analysis.com/favicon.ico",
+ 'logo': "https://www.hybrid-analysis.com/img/logo.svg",
+ 'description': "A free malware analysis service for the community. "
+ "Using this service you can submit files for in-depth static and dynamic analysis.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "verify": True,
+ "delay": 1
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "Hybrid Analysis API key.",
+ "verify": "Verify identified domains still resolve to the associated specified IP address.",
+ "delay": "Delay between requests, in seconds."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "DOMAIN_NAME"]
+
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "INTERNET_NAME", "DOMAIN_NAME", "LINKED_URL_INTERNAL"]
+
+ def queryDomain(self, qry):
+ """Query a domain
+
+ Args:
+ qry (str): domain
+
+ Returns:
+ str: API response as JSON
+ """
+
+ params = {
+ "domain": qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ "Accept": "application/json",
+ 'api-key': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl(
+ 'https://www.hybrid-analysis.com/api/v2/search/terms',
+ headers=headers,
+ timeout=15,
+ useragent="Falcon Sandbox",
+ postData=params
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def queryHost(self, qry):
+ """Query a host
+
+ Args:
+ qry (str): host
+
+ Returns:
+ str: API response as JSON
+ """
+
+ params = {
+ "host": qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ "Accept": "application/json",
+ 'api-key': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl(
+ 'https://www.hybrid-analysis.com/api/v2/search/terms',
+ headers=headers,
+ timeout=15,
+ useragent="Falcon Sandbox",
+ postData=params
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def queryHash(self, qry):
+ """Query a hash
+
+ Args:
+ qry (str): hash
+
+ Returns:
+ str: API response as JSON
+ """
+
+ params = {
+ "hash": qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ "Accept": "application/json",
+ 'api-key': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl(
+ 'https://www.hybrid-analysis.com/api/v2/search/hash',
+ headers=headers,
+ timeout=15,
+ useragent="Falcon Sandbox",
+ postData=params
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ """Parse HTTP response from API
+
+ Args:
+ res (dict): HTTP response from SpiderFoot.fetchUrl()
+
+ Returns:
+ str: API response as JSON
+ """
+ if not res:
+ self.error("No response from Hybrid Analysis.")
+ return None
+
+ if res['code'] == '400':
+ self.error("Failed to retrieve content from Hybrid Analysis: Invalid request")
+ self.debug(f"API response: {res['content']}")
+ return None
+
+ # Future proofing - Hybrid Analysis does not implement rate limiting
+ if res['code'] == '429':
+ self.error("Failed to retrieve content from Hybrid Analysis: rate limit exceeded")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error(f"Failed to retrieve content from Hybrid Analysis: Unexpected response status {res['code']}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName not in ["IP_ADDRESS", "DOMAIN_NAME"]:
+ return
+
+ if eventName == "IP_ADDRESS":
+ data = self.queryHost(eventData)
+ elif eventName == "DOMAIN_NAME":
+ data = self.queryDomain(eventData)
+ else:
+ return
+
+ if data is None:
+ self.debug(f"No information found for{eventData}")
+ return
+
+ results = data.get("result")
+
+ if not results:
+ return
+
+ hashes = []
+
+ for result in results:
+ file_hash = result.get('sha256')
+ if file_hash:
+ hashes.append(file_hash)
+
+ if not hashes:
+ return
+
+ self.info(f"Found {len(hashes)} results for {eventData}")
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ urls = []
+ domains = []
+
+ for file_hash in hashes:
+ results = self.queryHash(file_hash)
+
+ if not results:
+ self.debug(f"No information found for hash {file_hash}")
+ continue
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(results), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for result in results:
+ if not result:
+ continue
+
+ result_domains = result.get('domains')
+ if result_domains:
+ for r in result_domains:
+ domains.append(r)
+
+ submissions = result.get('submissions')
+ if submissions:
+ for submission in submissions:
+ url = submission.get('url')
+ if url:
+ urls.append(url)
+
+ for url in set(urls):
+ host = self.sf.urlFQDN(url.lower())
+
+ if not self.getTarget().matches(host, includeChildren=True, includeParents=True):
+ continue
+
+ domains.append(host)
+
+ evt = SpiderFootEvent('LINKED_URL_INTERNAL', url, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for domain in set(domains):
+ if self.checkForStop():
+ return
+
+ if domain in self.results:
+ continue
+
+ if not self.getTarget().matches(domain, includeChildren=True, includeParents=True):
+ continue
+
+ if self.opts['verify'] and not self.sf.resolveHost(domain) and not self.sf.resolveHost6(domain):
+ self.debug(f"Host {domain} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", domain, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("INTERNET_NAME", domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_hybrid_analysis class
diff --git a/spiderfoot/modules/sfp_iban.py b/spiderfoot/modules/sfp_iban.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca144945a702ffd892db113249b7a0cb2a260b89
--- /dev/null
+++ b/spiderfoot/modules/sfp_iban.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_iban
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and identifying IBANs.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 26/04/2020
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_iban(SpiderFootPlugin):
+
+ meta = {
+ 'name': "IBAN Number Extractor",
+ 'summary': "Identify International Bank Account Numbers (IBANs) in any data.",
+ 'flags': ["errorprone"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Override datasource for sfp_iban module
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT", "DARKNET_MENTION_CONTENT",
+ "LEAKSITE_CONTENT"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["IBAN_NUMBER"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ ibans = SpiderFootHelpers.extractIbansFromText(eventData)
+ for ibanNumber in set(ibans):
+ self.info(f"Found IBAN number: {ibanNumber}")
+ evt = SpiderFootEvent("IBAN_NUMBER", ibanNumber, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+# End of sfp_iban class
diff --git a/spiderfoot/modules/sfp_iknowwhatyoudownload.py b/spiderfoot/modules/sfp_iknowwhatyoudownload.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc417f12665dfd67d9fbc9301279c6f936c81387
--- /dev/null
+++ b/spiderfoot/modules/sfp_iknowwhatyoudownload.py
@@ -0,0 +1,165 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_iknowwhatyoudownload
+# Purpose: Query iknowwhatyoudownload.com for IP addresses using torrents.
+#
+# Author: Steve Micallef
+#
+# Created: 03/09/2018
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_iknowwhatyoudownload(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Iknowwhatyoudownload.com",
+ 'summary': "Check iknowwhatyoudownload.com for IP addresses that have been using torrents.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Secondary Networks"],
+ 'dataSource': {
+ 'website': "https://iknowwhatyoudownload.com/en/peer/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://iknowwhatyoudownload.com/en/api/",
+ "https://iknowwhatyoudownload.com/en/link/",
+ "https://iknowwhatyoudownload.com/en/peer/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://iknowwhatyoudownload.com/en/api/",
+ "Request Demo Key with email id",
+ "The API key will be sent to your email"
+ ],
+ 'favIcon': "https://iknowwhatyoudownload.com/assets/img/utorrent2.png",
+ 'logo': "https://iknowwhatyoudownload.com/assets/img/logo.png",
+ 'description': "Our system collects torrent files in two ways: parsing torrent sites, and listening DHT network. "
+ "The system contains more than 7 million torrents (as of Oct 2021) which were classified and which are using now "
+ "for collecting peer sharing facts (up to 200.000.000 daily).",
+ }
+ }
+
+ opts = {
+ "daysback": 30,
+ "api_key": ""
+ }
+
+ optdescs = {
+ "daysback": "How far back (in days) to look for activity.",
+ "api_key": "Iknowwhatyoudownload.com API key."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "IPV6_ADDRESS"]
+
+ def producedEvents(self):
+ return ["MALICIOUS_IPADDR"]
+
+ def query(self, qry):
+ """Search iknowwhatyoudownload.com for an IPv4/IPv6 address.
+
+ Args:
+ qry: IPv4/IPv6 address
+
+ Returns:
+ dict: JSON response containing dowloaded content
+ """
+ params = urllib.parse.urlencode({
+ 'ip': qry,
+ 'days': self.opts['daysback'],
+ 'key': self.opts['api_key'],
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.antitor.com/history/peer/?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot"
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from iknowwhatyoudownload.com.")
+ return None
+
+ if res['content'] is None:
+ self.info(f"No results for {qry} from iknowwhatyoudownload.com")
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from iknowwhatyoudownload.com: {e}")
+ return None
+
+ error = data.get('error')
+ if error and error == "INVALID_DAYS":
+ self.errorState = True
+ self.error(f"The number of days you have configured ({self.opts['daysback']}) was not accepted. If you have the demo key, try 30 days or less.")
+ return None
+
+ contents = data.get('contents')
+
+ if not contents:
+ return None
+
+ return contents
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_iknowwhatyoudownload but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+
+ if not data:
+ return
+
+ retdata = [f"https://iknowwhatyoudownload.com/en/peer/?ip={eventData} "]
+
+ for d in data:
+ torrent = d.get('torrent')
+
+ if not torrent:
+ continue
+
+ download_name = torrent.get('name')
+ download_date = d.get("endDate", "Date unknown")
+ retdata.append(f"{download_name} ({download_date})")
+
+ e = SpiderFootEvent("MALICIOUS_IPADDR", "\n".join(retdata), self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_iknowwhatyoudownload class
diff --git a/spiderfoot/modules/sfp_intelx.py b/spiderfoot/modules/sfp_intelx.py
new file mode 100644
index 0000000000000000000000000000000000000000..b87d37a299f7200e6acda4120872bb7ca531635c
--- /dev/null
+++ b/spiderfoot/modules/sfp_intelx.py
@@ -0,0 +1,293 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_intelx
+# Purpose: Query IntelligenceX (intelx.io) for identified IP addresses,
+# domains, e-mail addresses and phone numbers.
+#
+# Author: Steve Micallef
+#
+# Created: 28/04/2019
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import datetime
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_intelx(SpiderFootPlugin):
+
+ meta = {
+ 'name': "IntelligenceX",
+ 'summary': "Obtain information from IntelligenceX about identified IP addresses, domains, e-mail addresses and phone numbers.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://intelx.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://ginseg.com/wp-content/uploads/sites/2/2019/07/Manual-Intelligence-X-API.pdf",
+ "https://blog.intelx.io/2019/01/25/new-developer-tab/",
+ "https://github.com/IntelligenceX/SDK"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://intelx.io/",
+ "Register a free account",
+ "Navigate to https://intelx.io/account?tab=developer",
+ "The API key is listed under 'Your API details'"
+ ],
+ 'favIcon': "https://intelx.io/favicon/favicon-32x32.png",
+ 'logo': "https://intelx.io/assets/img/IntelligenceX.svg",
+ 'description': "Intelligence X is an independent European technology company founded in 2018 by Peter Kleissner. "
+ "Its mission is to develop and maintain the search engine and data archive.\n"
+ "The search works with selectors, i.e. specific search terms such as "
+ "email addresses, domains, URLs, IPs, CIDRs, Bitcoin addresses, IPFS hashes, etc.\n"
+ "It searches in places such as the darknet, document sharing platforms, whois data, public data leaks and others.\n"
+ "It keeps a historical data archive of results, "
+ "similar to how the Wayback Machine from archive.org stores historical copies of websites.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "base_url": "2.intelx.io",
+ "checkcohosts": False,
+ "checkaffiliates": False,
+ 'netblocklookup': False,
+ 'maxnetblock': 24,
+ 'subnetlookup': False,
+ 'maxsubnet': 24,
+ 'maxage': 90
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "IntelligenceX API key.",
+ "base_url": "API URL, as provided in your IntelligenceX account settings.",
+ "checkcohosts": "Check co-hosted sites?",
+ "checkaffiliates": "Check affiliates?",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxage': "Maximum age (in days) of results to be considered valid. 0 = unlimited."
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME", "EMAILADDR",
+ "CO_HOSTED_SITE", "PHONE_NUMBER", "BITCOIN_ADDRESS"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["LEAKSITE_URL", "DARKNET_MENTION_URL",
+ "INTERNET_NAME", "DOMAIN_NAME",
+ "EMAILADDR", "EMAILADDR_GENERIC"]
+
+ def query(self, qry, qtype):
+ retdata = list()
+
+ headers = {
+ "User-Agent": "SpiderFoot",
+ "x-key": self.opts['api_key'],
+ }
+
+ payload = {
+ "term": qry,
+ "buckets": [],
+ "lookuplevel": 0,
+ "maxresults": 100,
+ "timeout": 0,
+ "datefrom": "",
+ "dateto": "",
+ "sort": 4,
+ "media": 0,
+ "terminate": []
+ }
+
+ url = 'https://' + self.opts['base_url'] + '/' + qtype + '/search'
+ res = self.sf.fetchUrl(url, postData=json.dumps(payload),
+ headers=headers, timeout=self.opts['_fetchtimeout'])
+
+ if res['content'] is None:
+ self.info("No IntelligenceX info found for " + qry)
+ return None
+
+ if res['code'] == "402":
+ self.info("IntelligenceX credits expired.")
+ self.errorState = True
+ return None
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from IntelligenceX: {e}")
+ self.errorState = True
+ return None
+
+ if ret.get('status', -1) == 0:
+ # Craft API URL with the id to return results
+ resulturl = f"{url}/result?id={ret['id']}"
+ limit = 30
+ count = 0
+ status = 3 # status 3 = No results yet, keep trying. 0 = Success with results
+ while status in [3, 0] and count < limit:
+ if self.checkForStop():
+ return None
+
+ res = self.sf.fetchUrl(resulturl, headers=headers)
+ if res['content'] is None:
+ self.info("No IntelligenceX info found for results from " + qry)
+ return None
+
+ if res['code'] == "402":
+ self.info("IntelligenceX credits expired.")
+ self.errorState = True
+ return None
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.error("Error processing JSON response from IntelligenceX: " + str(e))
+ return None
+
+ status = ret['status']
+ count += 1
+
+ retdata.append(ret)
+ # No more results left
+ if status == 1:
+ # print data in json format to manipulate as desired
+ break
+
+ time.sleep(1)
+
+ return retdata
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "" or self.opts['base_url'] == "":
+ self.error("You enabled sfp_intelx but did not set an API key and/or base URL!")
+ self.errorState = True
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:
+ return
+
+ if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:
+ return
+
+ data = self.query(eventData, "intelligent")
+ if data is None:
+ return
+
+ self.info("Found IntelligenceX leak data for " + eventData)
+ agelimit = int(time.time() * 1000) - (86400000 * self.opts['maxage'])
+ for info in data:
+ for rec in info.get("records", dict()):
+ try:
+ last_seen = int(datetime.datetime.strptime(rec['added'].split(".")[0], '%Y-%m-%dT%H:%M:%S').strftime('%s')) * 1000
+ if self.opts['maxage'] > 0 and last_seen < agelimit:
+ self.debug("Record found but too old, skipping.")
+ continue
+
+ val = None
+ evt = None
+ if "pastes" in rec['bucket']:
+ evt = "LEAKSITE_URL"
+ val = rec['keyvalues'][0]['value']
+ if rec['bucket'].startswith("darknet."):
+ evt = "DARKNET_MENTION_URL"
+ val = rec['name']
+
+ if not val or not evt:
+ # Try generically extracting it
+ if "systemid" not in rec:
+ continue
+ evt = "LEAKSITE_URL"
+ val = "https://intelx.io/?did=" + rec['systemid']
+ except Exception as e:
+ self.error(f"Error processing content from IntelX: {e}")
+ continue
+
+ # Notify other modules of what you've found
+ e = SpiderFootEvent(evt, val, self.__name__, event)
+ self.notifyListeners(e)
+
+ if "public.intelx.io" in self.opts['base_url'] or eventName != "INTERNET_NAME":
+ return
+
+ data = self.query(eventData, "phonebook")
+ if data is None:
+ return
+
+ self.info(f"Found IntelligenceX host and email data for {eventData}")
+ for info in data:
+ for rec in info.get("selectors", dict()):
+ try:
+ val = rec['selectorvalueh']
+ evt = None
+ if rec['selectortype'] == 1: # Email
+ evt = "EMAILADDR"
+ if val.split("@")[0] in self.opts['_genericusers'].split(","):
+ evt = "EMAILADDR_GENERIC"
+ if rec['selectortype'] == 2: # Domain
+ evt = "INTERNET_NAME"
+ if val == eventData:
+ continue
+ if rec['selectortype'] == 3: # URL
+ evt = "LINKED_URL_INTERNAL"
+
+ if not val or not evt:
+ self.debug("Unexpected record, skipping.")
+ continue
+ except Exception as e:
+ self.error(f"Error processing content from IntelX: {e}")
+ continue
+
+ # Notify other modules of what you've found
+ e = SpiderFootEvent(evt, val, self.__name__, event)
+ self.notifyListeners(e)
+
+ if evt == "INTERNET_NAME" and self.sf.isDomain(val, self.opts['_internettlds']):
+ e = SpiderFootEvent("DOMAIN_NAME", val, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_intelx class
diff --git a/spiderfoot/modules/sfp_intfiles.py b/spiderfoot/modules/sfp_intfiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..2691442c74bc1bff360a05fb74207658a920f88f
--- /dev/null
+++ b/spiderfoot/modules/sfp_intfiles.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_intfiles
+# Purpose: From Spidered pages found, identifies files of potential interest.
+#
+# Author: Steve Micallef
+#
+# Created: 06/04/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_intfiles(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Interesting File Finder",
+ 'summary': "Identifies potential files of interest, e.g. office documents, zip files.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Crawling and Scanning"]
+ }
+
+ # Default options
+ opts = {
+ 'fileexts': ["doc", "docx", "ppt", "pptx", "pdf", 'xls', 'xlsx', 'zip']
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'fileexts': "File extensions of files you consider interesting."
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["INTERESTING_FILE"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ for fileExt in self.opts['fileexts']:
+ if "." + fileExt.lower() in eventData.lower():
+ evt = SpiderFootEvent("INTERESTING_FILE", eventData,
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_intfiles class
diff --git a/spiderfoot/modules/sfp_ipapico.py b/spiderfoot/modules/sfp_ipapico.py
new file mode 100644
index 0000000000000000000000000000000000000000..33fc6a29380cbd70ec9148b2b4bf0f5ea5755156
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipapico.py
@@ -0,0 +1,123 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipapico
+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses
+# identified by other modules using ipapi.co
+#
+# Author: Krishnasis Mandal
+#
+# Created: 02/02/2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipapico(SpiderFootPlugin):
+
+ meta = {
+ 'name': "ipapi.co",
+ 'summary': "Queries ipapi.co to identify geolocation of IP Addresses using ipapi.co API",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://ipapi.co/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://ipapi.co/api/"
+ ],
+ 'favIcon': "https://ipapi.co/static/images/favicon.b64f1de785e1.ico",
+ 'logo': "https://ipapi.co/static/images/favicon.34f0ec468301.png",
+ 'description': "Powerful & Simple REST API for IP Address Geolocation."
+ "ipapi.co provides a REST API to find the location of an IP address.",
+ }
+ }
+
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS"
+ ]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return [
+ "GEOINFO",
+ "RAW_RIR_DATA"
+ ]
+
+ def query(self, qry):
+ queryString = f"https://ipapi.co/{qry}/json/"
+
+ res = self.sf.fetchUrl(queryString,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+ time.sleep(1.5)
+
+ if res['content'] is None:
+ self.info(f"No ipapi.co data found for {qry}")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+
+ if data is None:
+ self.info("No results returned from ipapi.co")
+ return
+
+ if data.get('country'):
+ location = ', '.join(filter(None, [data.get('city'), data.get('region'), data.get('region_code'), data.get('country_name'), data.get('country')]))
+ evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+
+# End of sfp_ipapico class
diff --git a/spiderfoot/modules/sfp_ipapicom.py b/spiderfoot/modules/sfp_ipapicom.py
new file mode 100644
index 0000000000000000000000000000000000000000..d72056f34799b9177aab712de29b39f82029f44b
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipapicom.py
@@ -0,0 +1,144 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipapicom
+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses
+# identified by other modules using ipapi.com
+#
+# Author: Krishnasis Mandal
+#
+# Created: 29/01/2021
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipapicom(SpiderFootPlugin):
+
+ meta = {
+ 'name': "ipapi.com",
+ 'summary': "Queries ipapi.com to identify geolocation of IP Addresses using ipapi.com API",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://ipapi.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://ipapi.com/documentation"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://ipapi.com/",
+ "Register a free account",
+ "Browse to https://ipapi.com/dashboard",
+ "Your API Key will be listed under Your API Access Key",
+ ],
+ 'favIcon': "https://ipapi.com/site_images/ipapi_shortcut_icon.ico",
+ 'logo': "https://ipapi.com/site_images/ipapi_icon.png",
+ 'description': "ipapi provides an easy-to-use API interface allowing customers "
+ "to look various pieces of information IPv4 and IPv6 addresses are associated with. "
+ "For each IP address processed, the API returns more than 45 unique data points, "
+ "such as location data, connection data, ISP information, time zone, currency and security assessment data.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': '',
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': "ipapi.com API Key.",
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS"
+ ]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return [
+ "GEOINFO",
+ "RAW_RIR_DATA"
+ ]
+
+ def query(self, qry):
+ queryString = f"http://api.ipapi.com/api/{qry}?access_key={self.opts['api_key']}"
+
+ res = self.sf.fetchUrl(queryString,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+ time.sleep(1.5)
+
+ if res['code'] == "429":
+ self.error("You are being rate-limited by IP-API.com.")
+ self.errorState = True
+ return None
+ if res['content'] is None:
+ self.info(f"No ipapi.com data found for {qry}")
+ return None
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_ipapicom but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.query(eventData)
+ if not data:
+ return
+
+ if data.get('country_name'):
+ location = ', '.join(filter(None, [data.get('city'), data.get('region_name'), data.get('region_code'), data.get('country_name'), data.get('country_code')]))
+ evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('latitude') and data.get('longitude'):
+ evt = SpiderFootEvent("PHYSICAL_COORDINATES", f"{data.get('latitude')}, {data.get('longitude')}", self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+
+# End of sfp_ipapicom class
diff --git a/spiderfoot/modules/sfp_ipinfo.py b/spiderfoot/modules/sfp_ipinfo.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e8f973cc16b86612a93b414b6106bb0afc733f0
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipinfo.py
@@ -0,0 +1,138 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipinfo
+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses
+# identified by other modules using ipinfo.io.
+#
+# Author: Steve Micallef
+#
+# Created: 17/06/2017
+# Copyright: (c) Steve Micallef 2017
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipinfo(SpiderFootPlugin):
+
+ meta = {
+ 'name': "IPInfo.io",
+ 'summary': "Identifies the physical location of IP addresses identified using ipinfo.io.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://ipinfo.io",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://ipinfo.io/developers"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://ipinfo.io/",
+ "Sign up for a free account",
+ "Navigate to https://ipinfo.io/account",
+ "The API key is listed above 'is your access token'"
+ ],
+ 'favIcon': "https://ipinfo.io/static/favicon-96x96.png?v3",
+ 'logo': "https://ipinfo.io/static/deviceicons/android-icon-96x96.png",
+ 'description': "The Trusted Source for IP Address Data.\n"
+ "With IPinfo, you can pinpoint your users’ locations, customize their experiences, "
+ "prevent fraud, ensure compliance, and so much more.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": ""
+ }
+ optdescs = {
+ "api_key": "Ipinfo.io access token."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS', 'IPV6_ADDRESS']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["GEOINFO"]
+
+ # https://ipinfo.io/developers
+ def queryIP(self, ip):
+ headers = {
+ 'Authorization': "Bearer " + self.opts['api_key']
+ }
+ res = self.sf.fetchUrl("https://ipinfo.io/" + ip + "/json",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ headers=headers)
+
+ if res['code'] == "429":
+ self.error("You are being rate-limited by ipinfo.io.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.info("No GeoIP info found for " + ip)
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_ipinfo but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ data = self.queryIP(eventData)
+
+ if data is None:
+ return
+
+ if 'country' not in data:
+ return
+
+ location = ', '.join([_f for _f in [data.get('city'), data.get('region'), data.get('country')] if _f])
+ self.info("Found GeoIP for " + eventData + ": " + location)
+
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_ipinfo class
diff --git a/spiderfoot/modules/sfp_ipqualityscore.py b/spiderfoot/modules/sfp_ipqualityscore.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9bfccf9e188b91b3b0c20762cda3c07848362b8
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipqualityscore.py
@@ -0,0 +1,238 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipqualityscore
+# Purpose: Spiderfoot module to check whether a target is malicious
+# using IPQualityScore API
+#
+# Author: Krishnasis Mandal
+#
+# Created: 2020-10-07
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipqualityscore(SpiderFootPlugin):
+
+ meta = {
+ "name": "IPQualityScore",
+ "summary": "Determine if target is malicious using IPQualityScore API",
+ 'flags': ["apikey"],
+ "useCases": ["Investigate", "Passive"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://www.ipqualityscore.com/",
+ "model": "FREE_AUTH_LIMITED",
+ "references": [
+ "https://www.ipqualityscore.com/documentation/overview"
+ ],
+ "apiKeyInstructions": [
+ "Visit https://www.ipqualityscore.com/",
+ "Click on 'Plans'",
+ "Register a free account",
+ "Visit https://www.ipqualityscore.com/user/settings",
+ "Your API key will be listed under 'API Key'"
+ ],
+ "favIcon": "https://www.ipqualityscore.com/templates/img/icons/fav/favicon-32x32.png",
+ "logo": "https://www.ipqualityscore.com/templates/img/logo.png",
+ "description": "IPQualityScore's suite of fraud prevention tools automate quality control "
+ "to prevent bots, fake accounts, fraudsters, suspicious transactions, "
+ "& malicious users without interrupting the user experience.",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ "abuse_score_threshold": 85,
+ "strictness": 0
+ }
+
+ optdescs = {
+ "api_key": "IPQualityScore API Key",
+ "abuse_score_threshold": "Minimum abuse score for target to be considered malicious (0 - 100)",
+ "strictness": "Depth of the reputation checks to be performed on the target (0 - 2)"
+ }
+
+ errorState = False
+
+ def setup(self, sfc, userOpts=None):
+ if userOpts is None:
+ userOpts = {}
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return [
+ "DOMAIN_NAME",
+ "EMAILADDR",
+ "IP_ADDRESS",
+ "PHONE_NUMBER",
+ ]
+
+ def producedEvents(self):
+ return [
+ "EMAILADDR_DISPOSABLE",
+ "EMAILADDR_COMPROMISED",
+ "GEOINFO",
+ "MALICIOUS_PHONE_NUMBER",
+ "MALICIOUS_EMAILADDR",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_INTERNET_NAME",
+ "PHONE_NUMBER_TYPE",
+ "RAW_RIR_DATA"
+ ]
+
+ def handle_error_response(self, qry, res):
+ try:
+ error_info = json.loads(res["content"])
+ except Exception:
+ error_info = None
+ if error_info:
+ error_message = error_info.get("message")
+ else:
+ error_message = None
+ if error_message:
+ error_str = f", message {error_message}"
+ else:
+ error_str = ""
+ self.error(f"Failed to get results for {qry}, code {res['code']}{error_str}")
+
+ def query(self, qry, eventName):
+ queryString = ""
+ if eventName == "PHONE_NUMBER":
+ queryString = f"https://ipqualityscore.com/api/json/phone/{self.opts['api_key']}/{qry}?strictness={self.opts['strictness']}"
+ elif eventName == "EMAILADDR":
+ queryString = f"https://ipqualityscore.com/api/json/email/{self.opts['api_key']}/{qry}?strictness={self.opts['strictness']}"
+ elif eventName in ['IP_ADDRESS', 'DOMAIN_NAME']:
+ queryString = f"https://ipqualityscore.com/api/json/ip/{self.opts['api_key']}/{qry}?strictness={self.opts['strictness']}"
+
+ res = self.sf.fetchUrl(
+ queryString,
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+
+ if not res['content']:
+ self.info(f"No IPQualityScore info found for {qry}")
+ return None
+
+ try:
+ r = json.loads(res['content'])
+ if res["code"] != "200" or not r.get("success"):
+ self.handle_error_response(qry, res)
+ return None
+ return r
+ except Exception as e:
+ self.error(f"Error processing JSON response from IPQualityScore: {e}")
+
+ return None
+
+ def getGeoInfo(self, data):
+ geoInfo = ""
+
+ city = data.get('city')
+ country = data.get('country')
+ if not country:
+ country = data.get('country_code')
+ zipcode = data.get('zip_code')
+ region = data.get('region')
+
+ if city:
+ geoInfo += city + ", "
+ if region:
+ geoInfo += region + ", "
+ if country:
+ geoInfo += country + " "
+ if zipcode:
+ geoInfo += zipcode
+
+ return geoInfo
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API Key!"
+ )
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData} as already mapped.")
+ return
+ self.results[eventData] = True
+
+ data = self.query(eventData, eventName)
+ if not data:
+ return
+
+ fraudScore = data.get('fraud_score')
+ recentAbuse = data.get('recent_abuse')
+ botStatus = data.get('bot_status')
+ malicious = False
+ maliciousDesc = ""
+
+ if fraudScore >= self.opts['abuse_score_threshold'] or recentAbuse or botStatus:
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+ malicious = True
+ maliciousDesc = f"IPQualityScore [{eventData}]\n"
+
+ if eventName == "PHONE_NUMBER":
+ if malicious:
+ maliciousDesc += f" - FRAUD SCORE: {fraudScore}\n - ACTIVE: {data.get('active')}\n - RISKY: {data.get('risky')}\n - RECENT ABUSE: {recentAbuse}"
+ evt = SpiderFootEvent("MALICIOUS_PHONE_NUMBER", maliciousDesc, self.__name__, event)
+ self.notifyListeners(evt)
+
+ phoneNumberType = data.get('line_type')
+ if phoneNumberType:
+ evt = SpiderFootEvent("PHONE_NUMBER_TYPE", phoneNumberType, self.__name__, event)
+ self.notifyListeners(evt)
+
+ geoInfo = self.getGeoInfo(data)
+ if geoInfo:
+ evt = SpiderFootEvent("GEOINFO", geoInfo, self.__name__, event)
+ self.notifyListeners(evt)
+
+ elif eventName == "EMAILADDR":
+ if malicious:
+ maliciousDesc += f" - FRAUD SCORE: {fraudScore}\n - HONEYPOT: {data.get('honeypot')}\n - SPAM TRAP SCORE: {data.get('spam_trap_score')}\n - RECENT ABUSE: {recentAbuse}"
+ evt = SpiderFootEvent("MALICIOUS_EMAILADDR", maliciousDesc, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('disposable'):
+ evt = SpiderFootEvent("EMAILADDR_DISPOSABLE", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('leaked'):
+ evt = SpiderFootEvent("EMAILADDR_COMPROMISED", f"{eventData} [Unknown]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ elif eventName in ['IP_ADDRESS', 'DOMAIN_NAME']:
+ if malicious:
+ maliciousDesc += f" - FRAUD SCORE: {fraudScore}\n - BOT STATUS: {botStatus}\n - RECENT ABUSE: {recentAbuse}\n - ABUSE VELOCITY: {data.get('abuse_velocity')}\n - VPN: {data.get('vpn')}\n - ACTIVE VPN: {data.get('active_vpn')}\n - TOR: {data.get('tor')}\n - ACTIVE TOR: {data.get('active_tor')}"
+
+ if eventName == "IP_ADDRESS":
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", maliciousDesc, self.__name__, event)
+ elif eventName == "DOMAIN_NAME":
+ evt = SpiderFootEvent("MALICIOUS_INTERNET_NAME", maliciousDesc, self.__name__, event)
+ self.notifyListeners(evt)
+
+ geoInfo = self.getGeoInfo(data)
+ if geoInfo:
+ evt = SpiderFootEvent("GEOINFO", geoInfo, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_ipqualityscore class
diff --git a/spiderfoot/modules/sfp_ipregistry.py b/spiderfoot/modules/sfp_ipregistry.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0caf08ed2f44d2fd83a87cd470d0c82767cede6
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipregistry.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipregistry
+# Purpose: ipregistry database query module.
+#
+# Author: Leo Trubach
+#
+# Created: 2020-09-08
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib.parse
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipregistry(SpiderFootPlugin):
+ meta = {
+ "name": "ipregistry",
+ "summary": "Query the ipregistry.co database for reputation and geo-location.",
+ 'flags': ["apikey"],
+ "useCases": ["Passive", "Footprint", "Investigate"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://ipregistry.co/",
+ "model": "FREE_AUTH_LIMITED",
+ "references": ["https://ipregistry.co/docs"],
+ "apiKeyInstructions": [
+ "Visit https://dashboard.ipregistry.co/signup",
+ "Register a free account",
+ "Click on 'API Keys' in left navbar",
+ "Click on 'Click to reveal API key' for existing Default key",
+ ],
+ "favIcon": "https://cdn.ipregistry.co/icons/favicon-32x32.png",
+ "logo": "https://ipregistry.co/assets/ipregistry.svg",
+ "description": "Ipregistry is a trusted and in-depth IP "
+ "Geolocation and Threat detections source of information that can"
+ "benefit publishers, ad networks, retailers, financial services, "
+ "e-commerce stores and more.",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ }
+
+ optdescs = {
+ "api_key": "Ipregistry API Key.",
+ }
+
+ results = None
+
+ errorState = False
+
+ def setup(self, sfc, userOpts=None):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ if userOpts:
+ self.opts.update(userOpts)
+
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "IPV6_ADDRESS"]
+
+ def producedEvents(self):
+ return ["GEOINFO", "MALICIOUS_IPADDR", "PHYSICAL_COORDINATES", "RAW_RIR_DATA"]
+
+ def query(self, qry):
+ qs = urllib.parse.urlencode({"key": self.opts["api_key"]})
+ res = self.sf.fetchUrl(
+ f"https://api.ipregistry.co/{qry}?{qs}",
+ timeout=self.opts["_fetchtimeout"],
+ useragent="SpiderFoot",
+ )
+
+ if res["content"] is None:
+ self.info(f"No {self.meta['name']} info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res["content"])
+ except Exception as e:
+ self.error(
+ f"Error processing JSON response from {self.meta['name']}: {e}"
+ )
+
+ return None
+
+ def emit(self, etype, data, pevent):
+ evt = SpiderFootEvent(etype, data, self.__name__, pevent)
+ self.notifyListeners(evt)
+ return evt
+
+ def generate_location_events(self, location, pevent):
+ if not isinstance(location, dict):
+ return
+ physical_location = None
+ country = location.get("country")
+ if isinstance(country, dict):
+ country_name = country.get("name")
+ else:
+ country_name = None
+ region = location.get("region")
+ if isinstance(region, dict):
+ region_name = region.get("name")
+ else:
+ region_name = None
+ latitude = location.get("latitude")
+ longitude = location.get("longitude")
+ if latitude and longitude:
+ physical_location = f"{latitude}, {longitude}"
+ geo_info = ", ".join(
+ [
+ _f
+ for _f in [
+ location.get("city"),
+ region_name,
+ location.get("postal"),
+ country_name,
+ ]
+ if _f
+ ]
+ )
+ if geo_info:
+ self.emit("GEOINFO", geo_info, pevent)
+ if physical_location:
+ self.emit("PHYSICAL_COORDINATES", physical_location, pevent)
+
+ def generate_security_events(self, security, pevent):
+ if not isinstance(security, dict):
+ return
+ malicious = any(
+ security.get(k) for k in ("is_abuser", "is_attacker", "is_threat")
+ )
+ if malicious:
+ self.emit("MALICIOUS_IPADDR", f"ipregistry [{pevent.data}]", pevent)
+
+ def generate_events(self, data, pevent):
+ if not isinstance(data, dict):
+ return
+ self.generate_location_events(data.get("location"), pevent)
+ self.generate_security_events(data.get("security"), pevent)
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ if self.opts["api_key"] == "":
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
+ self.errorState = True
+ return
+
+ if event.data in self.results:
+ self.debug(f"Skipping {event.data}, already checked.")
+ return
+ self.results[event.data] = True
+
+ if event.eventType in ("IP_ADDRESS", "IPV6_ADDRESS"):
+ data = self.query(event.data)
+ self.generate_events(data, event)
+
+ self.emit("RAW_RIR_DATA", json.dumps(data), event)
diff --git a/spiderfoot/modules/sfp_ipstack.py b/spiderfoot/modules/sfp_ipstack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2deedf439056b9d999aeeab8e954c167f127738
--- /dev/null
+++ b/spiderfoot/modules/sfp_ipstack.py
@@ -0,0 +1,120 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_ipstack
+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses
+# identified by other modules using ipstack.com.
+#
+# Author: Steve Micallef
+#
+# Created: 20/08/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_ipstack(SpiderFootPlugin):
+
+ meta = {
+ 'name': "ipstack",
+ 'summary': "Identifies the physical location of IP addresses identified using ipstack.com.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://ipstack.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://ipstack.com/documentation",
+ "https://ipstack.com/faq"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://ipstack.com/product",
+ "Click on 'Get Free API Key'",
+ "Click on 'Dashboard'",
+ "The API key is listed under 'Your API Access Key'"
+ ],
+ 'favIcon': "https://ipstack.com/ipstack_images/ipstack_logo.svg",
+ 'logo': "https://ipstack.com/ipstack_images/ipstack_logo.svg",
+ 'description': "Locate and identify website visitors by IP address.\n"
+ "ipstack offers one of the leading IP to geolocation APIS "
+ "and global IP database services worldwide.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": ""
+ }
+ optdescs = {
+ "api_key": "Ipstack.com API key."
+ }
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS']
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["GEOINFO"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_ipstack but did not set an API key!")
+ self.errorState = True
+ return
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ res = self.sf.fetchUrl("http://api.ipstack.com/" + eventData + "?access_key=" + self.opts['api_key'],
+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+ if res['content'] is None:
+ self.info("No GeoIP info found for " + eventData)
+
+ try:
+ hostip = json.loads(res['content'])
+ if 'success' in hostip and hostip['success'] is False:
+ self.error("Invalid ipstack.com API key or usage limits exceeded.")
+ self.errorState = True
+ return
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return
+
+ geoinfo = hostip.get('country_name')
+ if geoinfo:
+ self.info(f"Found GeoIP for {eventData}: {geoinfo}")
+ evt = SpiderFootEvent("GEOINFO", geoinfo, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_ipstack class
diff --git a/spiderfoot/modules/sfp_isc.py b/spiderfoot/modules/sfp_isc.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fdd0420faa4fa95945f9560185a7e490a44251d
--- /dev/null
+++ b/spiderfoot/modules/sfp_isc.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_isc
+# Purpose: Check if an IP address is malicious according to SANS ISC.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_isc(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Internet Storm Center",
+ 'summary': "Check if an IP address is malicious according to SANS ISC.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://isc.sans.edu",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://isc.sans.edu/api/",
+ "https://isc.sans.edu/howto.html",
+ "https://isc.sans.edu/honeypot.html",
+ "https://isc.sans.edu/glossary.html",
+ "https://isc.sans.edu/fightback.html"
+ ],
+ 'favIcon': "https://isc.sans.edu/iscfavicon.ico",
+ 'logo': "https://isc.sans.edu/images/logos/isc/large.png",
+ 'description': "The ISC provides a free analysis and warning service to thousands of Internet users "
+ "and organizations, and is actively working with Internet Service Providers to "
+ "fight back against the most malicious attackers.\n"
+ "Thousands of sensors that work with most firewalls, intrusion detection systems, "
+ "home broadband devices, and nearly all operating systems are constantly collecting information about "
+ "unwanted traffic arriving from the Internet. "
+ "These devices feed the DShield database where human volunteers as well as machines pour through "
+ "the data looking for abnormal trends and behavior. "
+ "The resulting analysis is posted to the ISC's main web page where it can be automatically retrieved "
+ "by simple scripts or can be viewed in near real time by any Internet user.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ ]
+
+ def query(self, ip):
+ if not ip:
+ return None
+
+ res = self.sf.fetchUrl(
+ f"https://isc.sans.edu/api/ip/{ip}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from ISC.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from ISC")
+ self.errorState = True
+ return None
+
+ return res['content']
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ malicious_type = 'MALICIOUS_IPADDR'
+ blacklist_type = 'BLACKLISTED_IPADDR'
+ elif eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = 'MALICIOUS_AFFILIATE_IPADDR'
+ blacklist_type = 'BLACKLISTED_AFFILIATE_IPADDR'
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ data = self.query(eventData)
+
+ if not data:
+ return
+
+ attacks = re.findall(r"([0-9]+) ", data)
+
+ if not attacks:
+ return
+
+ url = f"https://isc.sans.edu/api/ip/{eventData}"
+ text = f"Internet Storm Center [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_isc class
diff --git a/spiderfoot/modules/sfp_jsonwhoiscom.py b/spiderfoot/modules/sfp_jsonwhoiscom.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cf1dac34adb154b5fed3e3bb14bf1f40fdf7db0
--- /dev/null
+++ b/spiderfoot/modules/sfp_jsonwhoiscom.py
@@ -0,0 +1,288 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_jsonwhoiscom
+# Purpose: Search JsonWHOIS.com for WHOIS records associated with a domain.
+#
+# Authors:
+#
+# Created: 2020-06-20
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_jsonwhoiscom(SpiderFootPlugin):
+
+ meta = {
+ 'name': "JsonWHOIS.com",
+ 'summary': "Search JsonWHOIS.com for WHOIS records associated with a domain.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://jsonwhois.com",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://jsonwhois.com/docs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://jsonwhois.com",
+ "Sign up for a free account",
+ "Navigate to https://jsonwhois.com/dashboard",
+ "The API key is listed under 'Api Key'"
+ ],
+ 'favIcon': "https://jsonwhois.com/assets/fav.ico",
+ 'logo': "https://jsonwhois.com/assets/fav.ico",
+ 'description': "Get access to accurate Whois records for generic and country TLDs. "
+ "Around 1000 gTLDs include .com, .org, .net, .us, .biz, .info, .mobi, .pro, .asia and many other new ones.\n"
+ "Raw and parsed Whois data are both accessible for downloads in the form of "
+ "MYSQL or MYSQL database dumps and Comma Separated Values (.CSV) files.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "delay": 1,
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "JsonWHOIS.com API key.",
+ "delay": "Delay between requests, in seconds.",
+ }
+
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "AFFILIATE_DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "DOMAIN_REGISTRAR", "DOMAIN_WHOIS", "PROVIDER_DNS",
+ "EMAILADDR", "EMAILADDR_GENERIC", "PHONE_NUMBER", "PHYSICAL_ADDRESS",
+ "AFFILIATE_DOMAIN_UNREGISTERED"]
+
+ # Query domain
+ # https://jsonwhois.com/docs
+ def queryDomain(self, qry):
+ params = {
+ 'domain': qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+ headers = {
+ "Accept": "application/json",
+ "Authorization": "Token token=" + self.opts["api_key"]
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://jsonwhois.com/api/v1/whois?{urllib.parse.urlencode(params)}",
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from JsonWHOIS.com.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results for query")
+ return None
+
+ # Sometimes JsonWHOIS.com returns HTTP 500 errors rather than 404
+ if res['code'] == '500' and res['content'] == '{"error":"Call failed"}':
+ self.debug("No results for query")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid JsonWHOIS.com API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by JsonWHOIS.com")
+ self.errorState = True
+ return None
+
+ if res['code'] == '503':
+ self.error("JsonWHOIS.com service unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all other non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from JsonWHOIS.com")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_jsonwhoiscom but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ res = self.queryDomain(eventData)
+
+ if res is None:
+ self.debug(f"No information found for domain {eventData}")
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(res), self.__name__, event)
+ self.notifyListeners(evt)
+
+ dns_providers = list()
+
+ nameservers = res.get('nameservers')
+ if nameservers:
+ for nameserver in nameservers:
+ if nameserver:
+ nameserver_name = nameserver.get('name')
+ if nameserver_name:
+ dns_providers.append(nameserver_name)
+
+ contacts = list()
+
+ registrant_contacts = res.get('registrant_contacts')
+ if registrant_contacts:
+ for contact in registrant_contacts:
+ contacts.append(contact)
+
+ admin_contacts = res.get('admin_contacts')
+ if admin_contacts:
+ for contact in admin_contacts:
+ contacts.append(contact)
+
+ technical_contacts = res.get('technical_contacts')
+ if technical_contacts:
+ for contact in technical_contacts:
+ contacts.append(contact)
+
+ emails = list()
+ names = list()
+ phones = list()
+ locations = list()
+
+ for contact in contacts:
+ email = contact.get('email')
+ if email:
+ if SpiderFootHelpers.validEmail(email):
+ emails.append(email)
+
+ name = contact.get("name")
+ if name:
+ names.append(name)
+
+ phone = contact.get('phone')
+ if phone:
+ phone = phone.replace(" ", "").replace("-", "").replace("(", "").replace(")", "").replace(".", "")
+ phones.append(phone)
+
+ country = SpiderFootHelpers.countryNameFromCountryCode(contact.get('country_code'))
+ location = ', '.join([_f for _f in [contact.get('address'), contact.get('city'), contact.get('state'), contact.get('zip'), country] if _f])
+ if location:
+ locations.append(location)
+
+ for email in set(emails):
+ mail_domain = email.lower().split('@')[1]
+ if self.getTarget().matches(mail_domain, includeChildren=True):
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("AFFILIATE_EMAILADDR", email, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName in ["DOMAIN_NAME"]:
+ raw = res.get('raw')
+ if raw:
+ evt = SpiderFootEvent("DOMAIN_WHOIS", raw, self.__name__, event)
+ self.notifyListeners(evt)
+
+ registrar = res.get("registrar")
+ if registrar:
+ registrar_name = registrar.get("name")
+ if registrar_name:
+ evt = SpiderFootEvent("DOMAIN_REGISTRAR", registrar_name, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for dns_provider in set(dns_providers):
+ evt = SpiderFootEvent("PROVIDER_DNS", dns_provider, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for name in set(names):
+ evt = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name {name}", self.__name__, event)
+ self.notifyListeners(evt)
+
+ for phone in set(phones):
+ evt = SpiderFootEvent("PHONE_NUMBER", phone, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for location in set(locations):
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName in ["AFFILIATE_DOMAIN_NAME"]:
+ raw = res.get('raw')
+ if raw:
+ evt = SpiderFootEvent("AFFILIATE_DOMAIN_WHOIS", raw, self.__name__, event)
+ self.notifyListeners(evt)
+
+ available = res.get('available?')
+ if available:
+ evt = SpiderFootEvent("AFFILIATE_DOMAIN_UNREGISTERED", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_jsonwhoiscom class
diff --git a/spiderfoot/modules/sfp_junkfiles.py b/spiderfoot/modules/sfp_junkfiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd40567df0dd38e2c35199e2962c35833229ef99
--- /dev/null
+++ b/spiderfoot/modules/sfp_junkfiles.py
@@ -0,0 +1,217 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_junkfiles
+# Purpose: From Spidering, identifies backup and temporary files.
+#
+# Author: Steve Micallef
+#
+# Created: 23/08/2014
+# Copyright: (c) Steve Micallef 2014
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import random
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_junkfiles(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Junk File Finder",
+ 'summary': "Looks for old/temporary and other similar files.",
+ 'flags': ["slow", "errorprone", "invasive"],
+ 'useCases': ["Footprint"],
+ 'categories': ["Crawling and Scanning"]
+ }
+
+ # Default options
+ opts = {
+ 'fileexts': ['tmp', 'bak', 'old'],
+ 'urlextstry': ['asp', 'php', 'jsp', ],
+ 'files': ["old", "passwd", ".htaccess", ".htpasswd",
+ "Thumbs.db", "backup"],
+ 'dirs': ['zip', 'tar.gz', 'tgz', 'tar']
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'fileexts': "File extensions to try.",
+ 'urlextstry': "Try those extensions against URLs with these extensions.",
+ 'files': "Try to fetch each of these files from the directory of the URL.",
+ 'dirs': "Try to fetch the containing folder with these extensions."
+ }
+
+ results = None
+ hosts = None
+ skiphosts = None
+ bases = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.hosts = self.tempStorage()
+ self.skiphosts = self.tempStorage()
+ self.bases = self.tempStorage()
+ self.__dataSource__ = "Target Website"
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["LINKED_URL_INTERNAL"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["JUNK_FILE"]
+
+ # Test how trustworthy a result is
+ def checkValidity(self, junkUrl):
+ # Try and fetch an obviously missing version of the junk file
+ fetch = junkUrl + str(random.SystemRandom().randint(0, 99999999))
+ res = self.sf.fetchUrl(fetch, headOnly=True,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False)
+ if res['code'] != "404":
+ host = SpiderFootHelpers.urlBaseUrl(junkUrl)
+ self.skiphosts[host] = True
+ return False
+ return True
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ host = SpiderFootHelpers.urlBaseUrl(eventData)
+
+ if host in self.skiphosts:
+ self.debug("Skipping " + host + " because it doesn't return 404s.")
+ return
+
+ # http://www/blah/abc.php -> try http://www/blah/abc.php.[fileexts]
+ for ext in self.opts['urlextstry']:
+ if host in self.skiphosts:
+ self.debug("Skipping " + host + " because it doesn't return 404s.")
+ return
+
+ if "." + ext + "?" in eventData or "." + ext + "#" in eventData or \
+ eventData.endswith("." + ext):
+ bits = eventData.split("?")
+ for x in self.opts['fileexts']:
+ if self.checkForStop():
+ return
+
+ self.debug("Trying " + x + " against " + eventData)
+ fetch = bits[0] + "." + x
+ if fetch in self.results:
+ self.debug("Skipping, already fetched.")
+ continue
+
+ self.results[fetch] = True
+
+ res = self.sf.fetchUrl(fetch, headOnly=True,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ sizeLimit=10000000,
+ verify=False)
+ if res['realurl'] != fetch:
+ self.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)
+ continue
+ if res['code'] == "200":
+ if not self.checkValidity(fetch):
+ continue
+
+ evt = SpiderFootEvent("JUNK_FILE", fetch, self.__name__, event)
+ self.notifyListeners(evt)
+
+ base = SpiderFootHelpers.urlBaseDir(eventData)
+ if not base or base in self.bases:
+ return
+
+ self.bases[base] = True
+
+ # http://www/blah/abc.html -> try http://www/blah/[files]
+ for f in self.opts['files']:
+ if self.checkForStop():
+ return
+
+ if host in self.skiphosts:
+ self.debug("Skipping " + host + " because it doesn't return 404s.")
+ return
+
+ self.debug("Trying " + f + " against " + eventData)
+ fetch = base + f
+ if fetch in self.results:
+ self.debug("Skipping, already fetched.")
+ continue
+
+ self.results[fetch] = True
+
+ res = self.sf.fetchUrl(fetch, headOnly=True,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False)
+ if res['realurl'] != fetch:
+ self.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)
+ continue
+ if res['code'] == "200":
+ if not self.checkValidity(fetch):
+ continue
+
+ evt = SpiderFootEvent("JUNK_FILE", fetch, self.__name__, event)
+ self.notifyListeners(evt)
+
+ # don't do anything with the root directory of a site
+ self.debug(f"Base: {base}, event: {eventData}")
+ if base in [eventData, eventData + "/"]:
+ return
+
+ # http://www/blah/abc.html -> try http://www/blah.[dirs]
+ for dirfile in self.opts['dirs']:
+ if self.checkForStop():
+ return
+
+ if host in self.skiphosts:
+ self.debug("Skipping " + host + " because it doesn't return 404s.")
+ return
+
+ if base.count('/') == 3:
+ self.debug("Skipping base url.")
+ continue
+
+ self.debug("Trying " + dirfile + " against " + eventData)
+ fetch = base[0:len(base) - 1] + "." + dirfile
+ if fetch in self.results:
+ self.debug("Skipping, already fetched.")
+ continue
+
+ self.results[fetch] = True
+
+ res = self.sf.fetchUrl(fetch, headOnly=True,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False)
+ if res['realurl'] != fetch:
+ self.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)
+ continue
+ if res['code'] == "200":
+ if not self.checkValidity(fetch):
+ continue
+
+ evt = SpiderFootEvent("JUNK_FILE", fetch, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_junkfiles class
diff --git a/spiderfoot/modules/sfp_keybase.py b/spiderfoot/modules/sfp_keybase.py
new file mode 100644
index 0000000000000000000000000000000000000000..98b882f40d45113c9edb95147a32826f7055a8b6
--- /dev/null
+++ b/spiderfoot/modules/sfp_keybase.py
@@ -0,0 +1,274 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_keybase
+# Purpose: Spiderfoot plugin to query KeyBase API
+# to gather additional information about domain names and identified
+# usernames.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 22/05/2020
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_keybase(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Keybase",
+ 'summary': "Obtain additional information about domain names and identified usernames.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Public Registries"],
+ 'dataSource': {
+ 'website': "https://keybase.io/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://keybase.io/docs/api/1.0/call/user/lookup",
+ ],
+ 'favIcon': "https://keybase.io/images/icons/icon-keybase-logo-48.png",
+ 'logo': "https://keybase.io/images/icons/icon-keybase-logo-48.png",
+ 'description': "Keybase is a key directory that maps social media identities to encryption keys "
+ "in a publicly auditable manner.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["USERNAME", "LINKED_URL_EXTERNAL", "DOMAIN_NAME"]
+
+ def producedEvents(self):
+ return [
+ "RAW_RIR_DATA", "SOCIAL_MEDIA", "USERNAME",
+ "GEOINFO", "BITCOIN_ADDRESS", "PGP_KEY"
+ ]
+
+ def query(self, selector: str, qry: str) -> str:
+ """Search Keybase for a domain name or username.
+
+ Args:
+ selector (str): query type ("usernames" | "domain")
+ qry (str): username
+
+ Returns:
+ str: Search results as JSON string
+ """
+ if not selector:
+ return None
+
+ if not qry:
+ return None
+
+ params = {
+ selector: qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+ }
+
+ headers = {
+ 'Accept': "application/json"
+ }
+
+ res = self.sf.fetchUrl(
+ 'https://keybase.io/_/api/1.0/user/lookup.json?' + urllib.parse.urlencode(params),
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent']
+ )
+
+ # In this case, it will always be 200 if keybase is queried
+ # The actual response codes are stored in status tag of the response
+ if res['code'] != '200':
+ self.error(f"Unexpected reply from Keybase: {res['code']}")
+ return None
+
+ try:
+ content = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ status = content.get('status')
+ if not status:
+ return None
+
+ code = status.get('code')
+
+ if code != 0:
+ self.error(f"Unexpected JSON response code reply from Keybase: {code}")
+ return None
+
+ them = content.get('them')
+ if not isinstance(them, list):
+ return None
+
+ return them
+
+ def handleEvent(self, event) -> None:
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ # Extract username if a Keybase link is received
+ if eventName == "LINKED_URL_EXTERNAL":
+ linkRegex = r"^https?://keybase.io\/[A-Za-z0-9\-_\.]+"
+ links = re.findall(linkRegex, eventData)
+
+ if len(links) == 0:
+ self.debug(f"Skipping URL {eventData}, as not a keybase link")
+ return
+
+ userName = links[0].split("/")[3]
+
+ data = self.query('usernames', userName)
+ elif eventName == "USERNAME":
+ data = self.query('usernames', eventData)
+ elif eventName == "DOMAIN_NAME":
+ data = self.query('domain', eventData)
+ else:
+ return
+
+ if not data:
+ self.debug(f"No data found for {eventName}: {eventData}")
+ return
+
+ for user in data:
+ if not user:
+ continue
+
+ # Basic information about the username
+ basics = user.get('basics')
+ if not basics:
+ continue
+
+ username = basics.get('username')
+ if not username:
+ continue
+
+ # Failsafe to prevent reporting any wrongly received data
+ if eventName == "USERNAME":
+ if eventData.lower() != username.lower():
+ self.error("Username does not match received response, skipping")
+ continue
+
+ # For newly discovereed usernames, create a username event to be used as a source event
+ if eventName in ['LINKED_URL_EXTERNAL', 'DOMAIN_NAME']:
+ if username in self.results:
+ self.debug(f"Skipping {userName}, already checked.")
+ continue
+
+ source_event = SpiderFootEvent("USERNAME", username, self.__name__, event)
+ self.notifyListeners(source_event)
+ self.results[username] = True
+ else:
+ source_event = event
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(user), self.__name__, source_event)
+ self.notifyListeners(evt)
+
+ # Profile information about the username
+ profile = user.get('profile')
+ if profile:
+ # Get and report full name of user
+ fullName = profile.get('full_name')
+ if fullName:
+ evt = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {fullName}", self.__name__, source_event)
+ self.notifyListeners(evt)
+
+ # Get and report location of user
+ location = profile.get('location')
+ if location:
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, source_event)
+ self.notifyListeners(evt)
+
+ # Extract social media information
+ proofsSummary = user.get('proofs_summary')
+
+ if proofsSummary:
+ socialMediaData = proofsSummary.get('all')
+
+ if socialMediaData:
+ for socialMedia in socialMediaData:
+ socialMediaSite = socialMedia.get('proof_type')
+ socialMediaURL = socialMedia.get('service_url')
+
+ if socialMediaSite and socialMediaURL:
+ socialMedia = socialMediaSite + ": " + "" + socialMediaURL + " "
+ evt = SpiderFootEvent("SOCIAL_MEDIA", socialMedia, self.__name__, source_event)
+ self.notifyListeners(evt)
+
+ # Get cryptocurrency addresses
+ cryptoAddresses = user.get('cryptocurrency_addresses')
+
+ # Extract and report bitcoin addresses if any
+ if cryptoAddresses:
+ bitcoinAddresses = cryptoAddresses.get('bitcoin')
+
+ if bitcoinAddresses:
+ for bitcoinAddress in bitcoinAddresses:
+ btcAddress = bitcoinAddress.get('address')
+
+ if not btcAddress:
+ continue
+
+ evt = SpiderFootEvent("BITCOIN_ADDRESS", btcAddress, self.__name__, source_event)
+ self.notifyListeners(evt)
+
+ # Extract PGP Keys
+ pgpRegex = r"-----BEGIN\s*PGP\s*(?:PUBLIC?)\s*KEY\s*BLOCK-----(.*?)-----END\s*PGP\s*(?:PUBLIC?)\s*KEY\s*BLOCK-----"
+
+ pgpKeys = re.findall(pgpRegex, str(user))
+
+ for pgpKey in pgpKeys:
+ if len(pgpKey) < 300:
+ self.debug(f"PGP key size ({len(pgpKey)} bytes) is likely invalid (smaller than 300 bytes), skipping.")
+ continue
+
+ # Remove unescaped \n literals
+ pgpKey = pgpKey.replace("\\n", "\n")
+
+ # Avoid reporting of duplicate keys
+ pgpKeyHash = self.sf.hashstring(pgpKey)
+
+ if pgpKeyHash in self.results:
+ continue
+
+ self.results[pgpKeyHash] = True
+
+ evt = SpiderFootEvent("PGP_KEY", pgpKey, self.__name__, source_event)
+ self.notifyListeners(evt)
+
+# End of sfp_keybase class
diff --git a/spiderfoot/modules/sfp_koodous.py b/spiderfoot/modules/sfp_koodous.py
new file mode 100644
index 0000000000000000000000000000000000000000..6257abe848b1d9ecdf0afd599fc426de581965ea
--- /dev/null
+++ b/spiderfoot/modules/sfp_koodous.py
@@ -0,0 +1,239 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_koodous
+# Purpose: Query Koodous for mobile apps.
+#
+# Author:
+#
+# Created: 2020-09-19
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_koodous(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Koodous",
+ 'summary': "Search Koodous for mobile apps.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'model': "FREE_AUTH_LIMITED",
+ "apiKeyInstructions": [
+ "Visit https://koodous.com/apks",
+ "Register a free account",
+ "Visit https://koodous.com/settings/developers and use the authentication token provided",
+ ],
+ 'references': [
+ "https://docs.koodous.com/api/apks.html",
+ "https://docs.koodous.com/apks.html#apks-search-system"
+ ],
+ 'website': "https://koodous.com/apks/",
+ 'favIcon': "https://koodous.com/favicon.ico",
+ 'logo': "https://koodous.com/assets/img/koodous-logo.png",
+ "description": "The Collaborative Platform for Android Malware Analysts."
+ }
+ }
+
+ opts = {
+ "api_key": "",
+ 'max_pages': 10,
+ }
+
+ optdescs = {
+ "api_key": "Koodous API key.",
+ 'max_pages': "Maximum number of pages of results to fetch.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.errorState = False
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'DOMAIN_NAME'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'APPSTORE_ENTRY',
+ 'RAW_RIR_DATA'
+ ]
+
+ def queryPackageName(self, qry, cursor=''):
+ package_name = qry.encode('raw_unicode_escape').decode("ascii", errors='replace')
+
+ params = urllib.parse.urlencode({
+ 'cursor': cursor,
+ 'search': f"package:{package_name}.*"
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://developer.koodous.com/apks/?{params}",
+ headers={"Authorization": f"Token {self.opts['api_key']}"},
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['_fetchtimeout']
+ )
+
+ # 100 requests per minute
+ time.sleep(1)
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Koodous.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results from Koodous.")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid Koodous API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by Koodous.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '500' or res['code'] == '502' or res['code'] == '503':
+ self.error("Koodous service is unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error(f"Unexpected reply from Koodous: {res['code']}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from Koodous: {e}")
+
+ return None
+
+ def handleEvent(self, event):
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {event.eventType}, from {event.module}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ # Reverse domain name to create potential package name
+ domain_reversed = '.'.join(list(reversed(eventData.lower().split('.'))))
+
+ max_pages = int(self.opts['max_pages'])
+ page = 1
+ cursor = ''
+ while page <= max_pages:
+ found = False
+
+ if self.checkForStop():
+ return
+
+ data = self.queryPackageName(domain_reversed, cursor)
+
+ page += 1
+
+ if not data:
+ self.errorState = True
+ return
+
+ results = data.get('results')
+
+ for result in results:
+ package_name = result.get('package_name')
+
+ if not package_name:
+ continue
+
+ app = result.get('app')
+
+ # results can have a null app name, but it is probably a duplicate
+ if not app:
+ continue
+
+ # TODO: compare company name with target
+ # company = result.get('company')
+
+ version = result.get('version')
+
+ if version:
+ app_full_name = f"{app} {version} ({package_name})"
+ else:
+ app_full_name = f"{app} ({package_name})"
+
+ if (
+ domain_reversed != package_name.lower()
+ and not package_name.lower().startswith(f"{domain_reversed}.")
+ and not package_name.lower().endswith(f".{domain_reversed}")
+ and f".{domain_reversed}." not in package_name.lower()
+ ):
+ self.debug(f"App {app_full_name} does not match {domain_reversed}, skipping")
+ continue
+
+ sha256 = result.get('sha256')
+
+ if not sha256:
+ continue
+
+ app_data = f"{app_full_name}\nhttps://koodous.com/apks/{sha256} "
+
+ evt = SpiderFootEvent('APPSTORE_ENTRY', app_data, self.__name__, event)
+ self.notifyListeners(evt)
+ found = True
+
+ if found:
+ evt = SpiderFootEvent('RAW_RIR_DATA', json.dumps(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if not data.get('next'):
+ break
+
+ next_cursor = re.findall('cursor=(.+?)&', data.get('next'))
+ if not next_cursor:
+ break
+
+ cursor = urllib.parse.unquote(next_cursor[0])
+
+# End of sfp_koodous class
diff --git a/spiderfoot/modules/sfp_leakix.py b/spiderfoot/modules/sfp_leakix.py
new file mode 100644
index 0000000000000000000000000000000000000000..91e59134d22036a390392d1b22ac35998050566c
--- /dev/null
+++ b/spiderfoot/modules/sfp_leakix.py
@@ -0,0 +1,248 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_leakix
+# Purpose: Search LeakIX for host data leaks, open ports, software and geoip.
+#
+# Authors:
+#
+# Created: 2020-06-16
+# Copyright: (c) bcoles 2020
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_leakix(SpiderFootPlugin):
+
+ meta = {
+ 'name': "LeakIX",
+ 'summary': "Search LeakIX for host data leaks, open ports, software and geoip.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "https://leakix.net/",
+ 'model': "FREE_AUTH_UNLIMITED",
+ 'references': [
+ "https://leakix.net/api-documentation"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://leakix.net/",
+ "Register a free account",
+ "Go to your 'Settings'",
+ "Click on 'API key'",
+ "Click on 'Reset key' to generate a new key"
+ ],
+ 'favIcon': "https://leakix.net/public/img/favicon.png",
+ 'logo': "https://leakix.net/public/img/logoleakix-v1.png",
+ 'description': "LeakIX provides insights into devices and servers that are compromised "
+ "and compromised database schemas online.\n"
+ "In this scope we inspect found services for weak credentials.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': "",
+ 'delay': 1,
+ "verify": True,
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': "LeakIX API key",
+ 'delay': 'Delay between requests, in seconds.',
+ "verify": "Verify discovered hostnames are valid by checking if they still resolve.",
+ }
+
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["RAW_RIR_DATA", "GEOINFO", "TCP_PORT_OPEN",
+ "OPERATING_SYSTEM", "SOFTWARE_USED", "WEBSERVER_BANNER",
+ "LEAKSITE_CONTENT", "INTERNET_NAME"]
+
+ # Query host
+ # https://leakix.net/api-documentation
+ def queryApi(self, qryType, qry):
+ headers = {
+ "Accept": "application/json",
+ "api-key": self.opts["api_key"]
+ }
+ res = self.sf.fetchUrl(
+ 'https://leakix.net/' + qryType + '/' + qry,
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent']
+ )
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from LeakIX.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("Host not found")
+ return None
+
+ # Future proofing - LeakIX does not implement rate limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by LeakIX")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from LeakIX")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ ports = list()
+ hosts = list()
+ oses = list()
+ softwares = list()
+ ips = list()
+ banners = list()
+ locs = list()
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if self.opts['api_key'] == "":
+ self.debug("You enabled sfp_leakix but did not set an API key, results are limited")
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName in ["IP_ADDRESS", "DOMAIN_NAME"]:
+ if eventName == "IP_ADDRESS":
+ data = self.queryApi("host", eventData)
+ if eventName == "DOMAIN_NAME":
+ data = self.queryApi("domain", eventData)
+
+ if data is None:
+ self.debug("No information found for host " + eventData)
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ services = data.get("Services")
+
+ if services:
+ for service in services:
+ src = event
+ ipevt = None
+ hostname = service.get('host')
+ if hostname and eventName == "DOMAIN_NAME" and self.getTarget().matches(hostname) and hostname not in hosts:
+ if self.opts["verify"] and not self.sf.resolveHost(hostname) and not self.sf.resolveHost6(hostname):
+ self.debug(f"Host {hostname} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", hostname, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("INTERNET_NAME", hostname, self.__name__, event)
+ self.notifyListeners(evt)
+ src = evt
+ hosts.append(hostname)
+ ip = service.get('ip')
+ if ip and eventName != "IP_ADDRESS" and self.sf.validIP(ip) and ip not in ips:
+ evt = SpiderFootEvent("IP_ADDRESS", ip, self.__name__, src)
+ self.notifyListeners(evt)
+ ips.append(ip)
+ ipevt = evt
+ port = service.get('port')
+ if port and ip + ":" + port not in ports:
+ evt = SpiderFootEvent("TCP_PORT_OPEN", ip + ':' + port, self.__name__, src)
+ self.notifyListeners(evt)
+ ports.append(ip + ":" + port)
+ headers = service.get('headers')
+ if headers:
+ servers = headers.get('Server')
+ if servers:
+ for server in servers:
+ if server and server not in banners:
+ evt = SpiderFootEvent('WEBSERVER_BANNER', server, self.__name__, src)
+ self.notifyListeners(evt)
+ banners.append(server)
+
+ geoip = service.get('geoip')
+ if geoip:
+ location = ', '.join([_f for _f in [geoip.get('city_name'), geoip.get('region_name'), geoip.get('country_name')] if _f])
+ if location:
+ if ip and self.sf.validIP(ip) and ipevt:
+ # GEOINFO should be linked to an IP_ADDRESS
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, ipevt)
+ self.notifyListeners(evt)
+ locs.append(location)
+
+ software = service.get('software')
+ if software:
+ software_version = ' '.join([_f for _f in [software.get('name'), software.get('version')] if _f])
+ if software_version and software_version not in softwares:
+ evt = SpiderFootEvent("SOFTWARE_USED", software_version, self.__name__, src)
+ self.notifyListeners(evt)
+ softwares.append(software_version)
+
+ os = software.get('os')
+ if os and os not in oses:
+ evt = SpiderFootEvent('OPERATING_SYSTEM', os, self.__name__, src)
+ self.notifyListeners(evt)
+ oses.append(os)
+
+ leaks = data.get("Leaks")
+
+ if leaks:
+ for leak in leaks:
+ leak_protocol = leak.get('type')
+ hostname = leak.get('host')
+ # If protocol is web, our hostname not empty and is not an IP ,
+ # and doesn't belong to our target, discard ( happens when sharing Hosting/CDN IPs )
+ if leak_protocol == "web" and hostname and not self.sf.validIP(hostname) and not self.getTarget().matches(hostname):
+ continue
+ leak_data = leak.get('data')
+ if leak_data:
+ evt = SpiderFootEvent("LEAKSITE_CONTENT", leak_data, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_leakix class
diff --git a/spiderfoot/modules/sfp_maltiverse.py b/spiderfoot/modules/sfp_maltiverse.py
new file mode 100644
index 0000000000000000000000000000000000000000..bae9107736a65d1dc59cf1b4e94bfdf576b7a5d0
--- /dev/null
+++ b/spiderfoot/modules/sfp_maltiverse.py
@@ -0,0 +1,245 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_maltiverse
+# Purpose: Spiderfoot plugin to search Maltiverse API
+# for any malicious activity by the target
+#
+# Author: Krishnasis Mandal
+#
+# Created: 20/05/2020
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+from datetime import datetime
+
+from netaddr import IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_maltiverse(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Maltiverse",
+ 'summary': "Obtain information about any malicious activities involving IP addresses",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://maltiverse.com",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://maltiverse.com/faq",
+ "https://app.swaggerhub.com/apis-docs/maltiverse/api/1.0.0-oas3"
+ ],
+ 'favIcon': "https://maltiverse.com/favicon.ico",
+ 'logo': "https://maltiverse.com/assets/images/logo/logo.png",
+ 'description': "The Open IOC Search Engine.\n"
+ "Enhance your SIEM or Firewall and crosscheck your event data with "
+ "top quality Threat Intelligence information to highlight what requires action.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'subnetlookup': False,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'maxsubnet': 24,
+ "age_limit_days": 30
+ }
+
+ # Option descriptions. Delete any options not applicable to this module.
+ optdescs = {
+ 'checkaffiliates': "Check affiliates?",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ # For a list of all events, check sfdb.py.
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "NETBLOCK_OWNER", "NETBLOCK_MEMBER",
+ "AFFILIATE_IPADDR"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["IP_ADDRESS", "MALICIOUS_IPADDR", "RAW_RIR_DATA",
+ "MALICIOUS_AFFILIATE_IPADDR"]
+
+ # Check whether the IP Address is malicious using Maltiverse API
+ # https://app.swaggerhub.com/apis-docs/maltiverse/api/1.0.0-oas3#/IPv4/getIP
+ def queryIPAddress(self, qry):
+
+ headers = {
+ 'Accept': "application/json",
+ }
+
+ res = self.sf.fetchUrl(
+ 'https://api.maltiverse.com/ip/' + str(qry),
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "400":
+ self.error("Bad request. " + qry + " is not a valid IP Address")
+ return None
+
+ if res['code'] == "404":
+ self.error("API endpoint not found")
+ return None
+
+ if res['code'] != "200":
+ self.debug("No information found from Maltiverse for IP Address")
+ return None
+
+ try:
+ # Maltiverse returns \\n instead of \n in the response
+ data = str(res['content']).replace("\\n", " ")
+ return json.loads(data)
+ except Exception:
+ self.error("Incorrectly formatted data received as JSON response")
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Don't look up stuff twice
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'NETBLOCK_OWNER':
+ if not self.opts['netblocklookup']:
+ return
+
+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
+ self.debug("Network size bigger than permitted: "
+ + str(IPNetwork(eventData).prefixlen) + " > "
+ + str(self.opts['maxnetblock']))
+ return
+
+ if eventName == 'NETBLOCK_MEMBER':
+ if not self.opts['subnetlookup']:
+ return
+
+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:
+ self.debug("Network size bigger than permitted: "
+ + str(IPNetwork(eventData).prefixlen) + " > "
+ + str(self.opts['maxsubnet']))
+ return
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ # If user has enabled affiliate checking
+ if eventName == "AFFILIATE_IPADDR" and not self.opts['checkaffiliates']:
+ return
+ qrylist.append(eventData)
+
+ for addr in qrylist:
+
+ if self.checkForStop():
+ return
+
+ data = self.queryIPAddress(addr)
+
+ if data is None:
+ break
+
+ maliciousIP = data.get('ip_addr')
+
+ if maliciousIP is None:
+ continue
+
+ if addr != maliciousIP:
+ self.error("Reported address doesn't match requested, skipping")
+ continue
+
+ blacklistedRecords = data.get('blacklist')
+
+ if blacklistedRecords is None or len(blacklistedRecords) == 0:
+ self.debug("No blacklist information found for IP")
+ continue
+
+ # Data is reported about the IP Address
+ if eventName.startswith("NETBLOCK_"):
+ ipEvt = SpiderFootEvent("IP_ADDRESS", addr, self.__name__, event)
+ self.notifyListeners(ipEvt)
+
+ if eventName.startswith("NETBLOCK_"):
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, ipEvt)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ maliciousIPDesc = f"Maltiverse [{maliciousIP}]\n"
+
+ for blacklistedRecord in blacklistedRecords:
+ lastSeen = blacklistedRecord.get('last_seen')
+ if lastSeen is None:
+ continue
+
+ try:
+ lastSeenDate = datetime.strptime(str(lastSeen), "%Y-%m-%d %H:%M:%S")
+ except Exception:
+ self.error("Invalid date in JSON response, skipping")
+ continue
+
+ today = datetime.now()
+
+ difference = (today - lastSeenDate).days
+
+ if difference > int(self.opts["age_limit_days"]):
+ self.debug("Record found is older than age limit, skipping")
+ continue
+
+ maliciousIPDesc += " - DESCRIPTION : " + str(blacklistedRecord.get("description")) + "\n"
+
+ maliciousIPDescHash = self.sf.hashstring(maliciousIPDesc)
+
+ if maliciousIPDescHash in self.results:
+ continue
+
+ self.results[maliciousIPDescHash] = True
+
+ if eventName.startswith("NETBLOCK_"):
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", maliciousIPDesc, self.__name__, ipEvt)
+ elif eventName.startswith("AFFILIATE_"):
+ evt = SpiderFootEvent("MALICIOUS_AFFILIATE_IPADDR", maliciousIPDesc, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", maliciousIPDesc, self.__name__, event)
+
+ self.notifyListeners(evt)
+
+# End of sfp_maltiverse class
diff --git a/spiderfoot/modules/sfp_malwarepatrol.py b/spiderfoot/modules/sfp_malwarepatrol.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed2fbf235142755f3f0ddbe0f49267b438e141cc
--- /dev/null
+++ b/spiderfoot/modules/sfp_malwarepatrol.py
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_malwarepatrol
+# Purpose: SpiderFoot plug-in to search MalwarePatrol's daatabase for
+# potential malicious IPs/hostnames.
+#
+# Author: Steve Micallef
+#
+# Created: 25/07/2016
+# Copyright: (c) Steve Micallef 2016
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_malwarepatrol(SpiderFootPlugin):
+
+ meta = {
+ 'name': "MalwarePatrol",
+ 'summary': "Searches malwarepatrol.net's database of malicious URLs/IPs.",
+ 'flags': ["apikey"],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.malwarepatrol.net/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://www.malwarepatrol.net/tech-support/",
+ "https://www.malwarepatrol.net/integrations-formats-tip-siem-soar/",
+ "https://www.malwarepatrol.net/community-contribution-suspicious-emails/",
+ "https://www.malwarepatrol.net/non-commercial/#lists"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.malwarepatrol.net/free-guard-block-list/",
+ "Register a free account",
+ "The Password/Receipt number will be mailed to your email"
+ ],
+ 'favIcon': "https://www.malwarepatrol.net/wp-content/uploads/2020/02/rsz_12logo-150x150.png",
+ 'logo': "https://www.malwarepatrol.net/wp-content/uploads/2016/06/rsz_mp_logo_clear_-_small.png",
+ 'description': "Based in the USA and Brazil, our history is one of community spirit and dedication to "
+ "Internet security that began in 2005 when a group started sharing malicious links using a simple mailing list.\n"
+ "Collecting, analyzing, and sharing data for over a decade has allowed us "
+ "to develop an extensive network of sensors, sharing agreements, and community contributors. "
+ "The result is our vast database of unique and historically rich – “intelligent” – threat data.",
+ }
+ }
+
+ opts = {
+ "api_key": "",
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ }
+
+ optdescs = {
+ "api_key": "Malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed.",
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "CO_HOSTED_SITE",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryAddr(self, qaddr):
+ data = dict()
+ url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \
+ self.opts['api_key'] + "&product=8&list=smoothwall"
+
+ data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)
+ if data['content'] is None:
+ data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])
+ if data['content'] is None:
+ self.error("Unable to fetch " + url)
+ return None
+ self.sf.cachePut("sfmalwarepatrol", data['content'])
+
+ for line in data['content'].split('\n'):
+ if len(line) < 2 or line.startswith('#'):
+ continue
+
+ if line.startswith(qaddr):
+ return True
+
+ return False
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if not self.opts['api_key']:
+ self.error("You enabled sfp_malwarepatrol but did not provide a receipt ID!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData} as already searched.")
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ if not self.queryAddr(eventData):
+ return
+
+ text = f"MalwarePatrol [{eventData}]"
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_malwarepatrol class
diff --git a/spiderfoot/modules/sfp_metadefender.py b/spiderfoot/modules/sfp_metadefender.py
new file mode 100644
index 0000000000000000000000000000000000000000..20091610a7235cc979b2e9898030c5e58e5d2d5f
--- /dev/null
+++ b/spiderfoot/modules/sfp_metadefender.py
@@ -0,0 +1,237 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_metadefender
+# Purpose: Search MetaDefender API for IP address and domain reputation.
+#
+# Author:
+#
+# Created: 2019-09-21
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_metadefender(SpiderFootPlugin):
+
+ meta = {
+ 'name': "MetaDefender",
+ 'summary': "Search MetaDefender API for IP address and domain IP reputation.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://metadefender.opswat.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://onlinehelp.opswat.com/mdcloud/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://metadefender.opswat.com/",
+ "Register a free account",
+ "Navigate to https://metadefender.opswat.com/account",
+ "The API key is listed under 'API key'"
+ ],
+ 'favIcon': "https://mcl-cdn.opswat.com/1.40.3-729f31db/city/icons/icon-48x48.png?v=61be50566cce944a710aaa90ba6bbb8d",
+ 'logo': "https://mcl-cdn.opswat.com/1.40.3-729f31db/city/icons/icon-48x48.png?v=61be50566cce944a710aaa90ba6bbb8d",
+ 'description': "File Analysis - Analyzing binaries with 30+ anti-malware engines.\n"
+ "Heuristic analysis to detect more unknown and targeted attacks.\n"
+ "Binary vulnerability data assessment, IP/Domain reputation, Threat Intelligence Feeds",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': '',
+ # 10 requests / minute for free users
+ # 100 requests / minute for paid users
+ 'delay': 6
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': 'MetaDefender API key.',
+ 'delay': 'Delay between requests, in seconds.'
+ }
+
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS', 'INTERNET_NAME']
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ 'MALICIOUS_IPADDR',
+ 'MALICIOUS_INTERNET_NAME',
+ 'BLACKLISTED_IPADDR',
+ 'BLACKLISTED_INTERNET_NAME',
+ 'GEOINFO'
+ ]
+
+ # Query domain REST API
+ # https://onlinehelp.opswat.com/mdcloud/4.5_Domain_Reputation.html
+ def queryDomain(self, qry):
+ headers = {
+ 'Accept': 'application/json',
+ 'apikey': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl('https://api.metadefender.com/v4/domain/' + qry,
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query ip REST API
+ # https://onlinehelp.opswat.com/mdcloud/4.1_IP_Reputation.html
+ def queryIp(self, qry):
+ headers = {
+ 'Accept': 'application/json',
+ 'apikey': self.opts['api_key']
+ }
+ res = self.sf.fetchUrl('https://api.metadefender.com/v4/ip/' + qry,
+ headers=headers,
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from MetaDefender.")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid MetaDefender API key")
+ self.errorState = True
+ return None
+
+ # https://onlinehelp.opswat.com/mdcloud/3._Rate_Limiting.html
+ # https://onlinehelp.opswat.com/mdcloud/4._Throttling.html
+ if res['code'] == "429":
+ self.error("You are being rate-limited by MetaDefender")
+ self.errorState = True
+ return None
+
+ if res['code'] == "404":
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_metadefender but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventName == 'IP_ADDRESS':
+ data = self.queryIp(eventData)
+
+ if data is None:
+ self.debug("No matches found for " + eventData)
+ return
+
+ geo_info = data.get('geo_info')
+
+ if geo_info:
+ location = ', '.join([_f for _f in [geo_info.get('city').get('name'), geo_info.get('country').get('name')] if _f])
+ evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ res = data.get('lookup_results')
+
+ if not res:
+ self.debug("No matches found for " + eventData)
+ return
+
+ sources = res.get('sources')
+
+ if not sources:
+ self.debug("No matches found for " + eventData)
+ return
+
+ for m in sources:
+ if not m.get('assessment'):
+ continue
+ if m['assessment'] != "trustworthy":
+ continue
+ provider = m.get('provider')
+ evt = SpiderFootEvent('MALICIOUS_IPADDR', provider + ' [' + eventData + ']', self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent('BLACKLISTED_IPADDR', provider + ' [' + eventData + ']', self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == 'INTERNET_NAME':
+ data = self.queryDomain(eventData)
+
+ if data is None:
+ self.debug("No matches found for " + eventData)
+ return
+
+ res = data.get('lookup_results')
+
+ if not res:
+ self.debug("No matches found for " + eventData)
+ return
+
+ sources = res.get('sources')
+
+ if not sources:
+ self.debug("No matches found for " + eventData)
+ return
+
+ for m in sources:
+ if not m.get('assessment'):
+ continue
+ if m['assessment'] == "trustworthy":
+ continue
+ provider = m.get('provider')
+ evt = SpiderFootEvent('MALICIOUS_INTERNET_NAME', provider + ' [' + eventData + ']', self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent('BLACKLISTED_INTERNET_NAME', provider + ' [' + eventData + ']', self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_metadefender class
diff --git a/spiderfoot/modules/sfp_mnemonic.py b/spiderfoot/modules/sfp_mnemonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c4c141bb1bdf312e7e859591d009d33fea9faf1
--- /dev/null
+++ b/spiderfoot/modules/sfp_mnemonic.py
@@ -0,0 +1,288 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_mnemonic
+# Purpose: SpiderFoot plug-in for retrieving passive DNS information
+# from Mnemonic PassiveDNS API.
+#
+# Author:
+#
+# Created: 2018-10-12
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_mnemonic(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Mnemonic PassiveDNS",
+ 'summary': "Obtain Passive DNS information from PassiveDNS.mnemonic.no.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://www.mnemonic.no",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.mnemonic.no/resources/whitepapers/",
+ "https://www.mnemonic.no/research-and-development/",
+ "https://docs.mnemonic.no/display/public/API/PassiveDNS+Integration+Guide"
+ ],
+ 'favIcon': "https://www.mnemonic.no/favicon-96x96.png",
+ 'logo': "https://www.mnemonic.no/UI/logo.svg",
+ 'description': "mnemonic helps businesses manage their security risks, "
+ "protect their data and defend against cyber threats.\n"
+ "Our expert team of security consultants, product specialists, "
+ "threat researchers, incident responders and ethical hackers, combined "
+ "with our Argus security platform ensures we stay ahead of "
+ "advanced cyberattacks and protect our customers from evolving threats.",
+ }
+ }
+
+ opts = {
+ 'per_page': 500,
+ 'max_pages': 2,
+ 'timeout': 30,
+ 'maxage': 180, # 6 months
+ 'verify': True,
+ 'cohostsamedomain': False,
+ 'maxcohost': 100
+ }
+
+ optdescs = {
+ 'per_page': "Maximum number of results per page.",
+ 'max_pages': "Maximum number of pages of results to fetch.",
+ 'timeout': "Query timeout, in seconds.",
+ 'maxage': "The maximum age of the data returned, in days, in order to be considered valid.",
+ 'verify': "Verify identified domains still resolve to the associated specified IP address.",
+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ }
+
+ cohostcount = 0
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'IPV6_ADDRESS',
+ 'INTERNET_NAME',
+ 'DOMAIN_NAME'
+ ]
+
+ def producedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'IPV6_ADDRESS',
+ 'INTERNAL_IP_ADDRESS',
+ 'CO_HOSTED_SITE',
+ 'INTERNET_NAME',
+ 'DOMAIN_NAME'
+ ]
+
+ def query(self, qry, limit=500, offset=0):
+ """Query the Mnemonic PassiveDNS v3 API.
+
+ Args:
+ qry (str): domain name or IP address
+ limit (int): Limit the number of returned values.
+ offset (int): Skip the initial number of values in the resultset.
+
+ Returns:
+ dict: results as JSON
+ """
+
+ params = urllib.parse.urlencode({
+ 'limit': limit,
+ 'offset': offset
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.mnemonic.no/pdns/v3/{qry}?{params}",
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ # Unauthenticated users are limited to 100 requests per minute, and 1000 requests per day.
+ time.sleep(0.75)
+
+ if res['content'] is None:
+ self.info("No results found for " + qry)
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response from Mnemonic: {e}")
+ return None
+
+ response_code = data.get('responseCode')
+
+ if not response_code:
+ self.debug("Error retrieving search results.")
+ return None
+
+ if response_code == 402:
+ self.debug("Error retrieving search results: Resource limit exceeded")
+ self.errorState = True
+ return None
+
+ if response_code != 200:
+ self.debug(f"Error retrieving search results: {response_code}")
+ return None
+
+ if 'data' not in data:
+ self.info(f"No results found for {qry}")
+ return None
+
+ size = data.get('size')
+ count = data.get('count')
+
+ if not count or not size:
+ self.info(f"No results found for {qry}")
+ return None
+
+ self.info(f"Retrieved {size} of {count} results")
+
+ return data['data']
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ position = 0
+ max_pages = int(self.opts['max_pages'])
+ per_page = int(self.opts['per_page'])
+ agelimit = int(time.time() * 1000) - (86400000 * self.opts['maxage'])
+ self.cohostcount = 0
+ cohosts = list()
+
+ while position < (per_page * max_pages):
+ if self.checkForStop():
+ break
+
+ if self.errorState:
+ break
+
+ data = self.query(eventData, limit=per_page, offset=position)
+
+ if data is None:
+ self.info(f"No passive DNS data found for {eventData}")
+ break
+
+ position += per_page
+
+ for r in data:
+ if "*" in r['query'] or "%" in r['query']:
+ continue
+
+ if r['lastSeenTimestamp'] < agelimit:
+ self.debug(f"Record {r['answer']} found for {r['query']} is too old, skipping.")
+ continue
+
+ if eventName in ['IP_ADDRESS']:
+ if r['rrtype'] == 'a':
+ if self.sf.validIP(r['query']):
+ cohosts.append(r['query'])
+ continue
+
+ if eventName in ['INTERNET_NAME', 'DOMAIN_NAME']:
+ # Ignore PTR records
+ if r['rrtype'] == 'ptr':
+ continue
+
+ if r['rrtype'] == 'cname':
+ if not self.getTarget().matches(r['query'], includeParents=True):
+ continue
+
+ cohosts.append(r['query'])
+
+ if self.opts['verify']:
+ continue
+
+ answer = r.get('answer')
+
+ if r['rrtype'] == 'a':
+ if not self.sf.validIP(answer):
+ continue
+
+ if self.sf.isValidLocalOrLoopbackIp(answer):
+ evt = SpiderFootEvent("INTERNAL_IP_ADDRESS", answer, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("IP_ADDRESS", answer, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if r['rrtype'] == 'aaaa':
+ if not self.sf.validIP6(r['answer']):
+ continue
+
+ if self.sf.isValidLocalOrLoopbackIp(answer):
+ evt = SpiderFootEvent("INTERNAL_IP_ADDRESS", answer, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("IPV6_ADDRESS", answer, self.__name__, event)
+ self.notifyListeners(evt)
+
+ for co in set(cohosts):
+ if self.checkForStop():
+ return
+
+ if co in self.results:
+ continue
+
+ if eventName in ["IP_ADDRESS", "IPV6_ADDRESS"]:
+ if self.opts['verify'] and not self.sf.validateIP(co, eventData):
+ self.debug(f"Host {co} no longer resolves to {eventData}")
+ continue
+
+ if self.opts['cohostsamedomain']:
+ if self.cohostcount < self.opts['maxcohost']:
+ evt = SpiderFootEvent("CO_HOSTED_SITE", co, self.__name__, event)
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+ continue
+
+ if self.getTarget().matches(co, includeParents=True):
+ if self.opts['verify'] and not self.sf.resolveHost(co) and not self.sf.resolveHost6(co):
+ self.debug(f"Host {co} could not be resolved")
+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", co, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ evt = SpiderFootEvent("INTERNET_NAME", co, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(co, self.opts['_internettlds']):
+ evt = SpiderFootEvent("DOMAIN_NAME", co, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_mnemonic class
diff --git a/spiderfoot/modules/sfp_multiproxy.py b/spiderfoot/modules/sfp_multiproxy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebbceb951ccfe5d996fb80b3b65464afe68830a7
--- /dev/null
+++ b/spiderfoot/modules/sfp_multiproxy.py
@@ -0,0 +1,214 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_multiproxy
+# Purpose: Check if an IP arress is an open proxy according to multiproxy.org
+# open proxy list.
+#
+# Author: steve@binarypool.com
+#
+# Created: 14/12/2013
+# Copyright: (c) Steve Micallef, 2013
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from netaddr import IPAddress, IPNetwork
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_multiproxy(SpiderFootPlugin):
+
+ meta = {
+ 'name': "multiproxy.org Open Proxies",
+ 'summary': "Check if an IP address is an open proxy according to multiproxy.org open proxy list.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Secondary Networks"],
+ 'dataSource': {
+ 'website': "https://multiproxy.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://multiproxy.org/faq.htm",
+ "https://multiproxy.org/env_check.htm",
+ "https://multiproxy.org/anon_proxy.htm",
+ "https://multiproxy.org/help.htm"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://multiproxy.org/",
+ 'logo': "https://multiproxy.org/images/mproxy_title.png",
+ 'description': "MultiProxy is a multifunctional personal proxy server that protects your privacy "
+ "while on the Internet as well as speeds up your downloads, "
+ "especially if you are trying to get several files form overseas or from otherwise rather slow server. "
+ "It can also completely hide your IP address by dynamically connecting to "
+ "non-transparent anonymizing public proxy servers. "
+ "You can also test a list of proxy servers and sort them by connection speed and level of anonimity.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'cacheperiod': 18
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'cacheperiod': "Hours to cache list data before re-fetching."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ 'IP_ADDRESS',
+ 'AFFILIATE_IPADDR',
+ 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER',
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_IPADDR",
+ "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET",
+ "BLACKLISTED_NETBLOCK",
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET",
+ ]
+
+ def queryProxyList(self, target, targetType):
+ proxy_list = self.retrieveProxyList()
+
+ if not proxy_list:
+ self.errorState = True
+ return False
+
+ if targetType == "ip":
+ if target in proxy_list:
+ self.debug(f"IP address {target} found in multiproxy.org open proxy list.")
+ return True
+ elif targetType == "netblock":
+ netblock = IPNetwork(target)
+ for ip in proxy_list:
+ if IPAddress(ip) in netblock:
+ self.debug(f"IP address {ip} found within netblock/subnet {target} in multiproxy.org open proxy list.")
+ return True
+
+ return False
+
+ def retrieveProxyList(self):
+ proxy_list = self.sf.cacheGet('multiproxyopenproxies', 24)
+
+ if proxy_list is not None:
+ return self.parseProxyList(proxy_list)
+
+ res = self.sf.fetchUrl(
+ "http://multiproxy.org/txt_all/proxy.txt",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from multiproxy.org.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from multiproxy.org")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("multiproxyopenproxies", res['content'])
+
+ return self.parseProxyList(res['content'])
+
+ def parseProxyList(self, proxy_list):
+ """Parse plaintext open proxy list
+
+ Args:
+ proxy_list (str): plaintext open proxy list from multiproxy.org
+
+ Returns:
+ list: list of open proxy IP addresses
+ """
+ ips = list()
+
+ if not proxy_list:
+ return ips
+
+ for ip in proxy_list.split('\n'):
+ ip = ip.strip().split(":")[0]
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'IP_ADDRESS':
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_IPADDR"
+ blacklist_type = "BLACKLISTED_IPADDR"
+ elif eventName == 'AFFILIATE_IPADDR':
+ if not self.opts.get('checkaffiliates', False):
+ return
+ targetType = 'ip'
+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
+ elif eventName == 'NETBLOCK_OWNER':
+ if not self.opts.get('checknetblocks', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_NETBLOCK"
+ blacklist_type = "BLACKLISTED_NETBLOCK"
+ elif eventName == 'NETBLOCK_MEMBER':
+ if not self.opts.get('checksubnets', False):
+ return
+ targetType = 'netblock'
+ malicious_type = "MALICIOUS_SUBNET"
+ blacklist_type = "BLACKLISTED_SUBNET"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with multiproxy.org open proxy list")
+
+ if not self.queryProxyList(eventData, targetType):
+ return
+
+ url = "http://multiproxy.org/txt_all/proxy.txt"
+ text = f"multiproxy.org Open Proxies [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_multiproxy class
diff --git a/spiderfoot/modules/sfp_myspace.py b/spiderfoot/modules/sfp_myspace.py
new file mode 100644
index 0000000000000000000000000000000000000000..e00b582d5b0f14e67031fc73c93c2d2568956519
--- /dev/null
+++ b/spiderfoot/modules/sfp_myspace.py
@@ -0,0 +1,149 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_myspace
+# Purpose: Query MySpace for username and location information.
+#
+# Author:
+#
+# Created: 2018-10-07
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_myspace(SpiderFootPlugin):
+
+ meta = {
+ 'name': "MySpace",
+ 'summary': "Gather username and location from MySpace.com profiles.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Social Media"],
+ 'dataSource': {
+ 'website': "https://myspace.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.programmableweb.com/api/myspace"
+ ],
+ 'favIcon': "https://x.myspacecdn.com/new/common/images/favicons/favicon.ico",
+ 'logo': "https://x.myspacecdn.com/new/common/images/favicons/114-Retina-iPhone.png",
+ 'description': "Myspace is a place where people come to connect, discover, and share.\n"
+ "Through an open design, compelling editorial features, "
+ "and analytics-based recommendations, Myspace creates a creative community "
+ "of people who connect around mutual affinity and inspiration for the purpose "
+ "of shaping, sharing, and discovering what's next.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.__dataSource__ = "MySpace.com"
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["EMAILADDR", "SOCIAL_MEDIA"]
+
+ def producedEvents(self):
+ return ["SOCIAL_MEDIA", "GEOINFO"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # Search by email address
+ if eventName == "EMAILADDR":
+ email = eventData
+ res = self.sf.fetchUrl("https://myspace.com/search/people?q=" + email,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.error(f"Could not fetch MySpace content for {email}")
+ return
+
+ # Extract HTML containing potential profile matches
+ profiles = re.findall(r'[^<]+ ', str(res['content']))
+
+ if not profiles:
+ self.debug(f"No profiles found for e-mail: {email}")
+ return
+
+ # The first result is the closest match, but whether it's an exact match is unknown.
+ profile = profiles[0]
+
+ # Check for email address as name, at the risk of missed results.
+ try:
+ matches = re.findall(r'\.\?\!]+' + email + r'[\&; :\"\#\*\)\"\'\;\,\<\.\?\!]+', profile, re.IGNORECASE)
+ except Exception:
+ self.debug("Malformed e-mail address, skipping.")
+ return
+
+ if not matches:
+ self.debug("No concrete match for that e-mail.")
+ return
+
+ name = matches[0]
+ e = SpiderFootEvent(
+ "SOCIAL_MEDIA",
+ f"MySpace: https://myspace.com/{name} ",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(e)
+
+ # Retrieve location from MySpace profile
+ if eventName == "SOCIAL_MEDIA":
+ try:
+ network = eventData.split(": ")[0]
+ url = eventData.split(": ")[1].replace("", "").replace(" ", "")
+ except Exception as e:
+ self.debug(f"Unable to parse SOCIAL_MEDIA: {eventData} ({e})")
+ return
+
+ if network != "MySpace":
+ self.debug(f"Skipping social network profile, {url}, as not a MySpace profile")
+ return
+
+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ return
+
+ data = re.findall(r' 100:
+ self.debug("Skipping likely invalid location.")
+ return
+
+ e = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_myspace class
diff --git a/spiderfoot/modules/sfp_nameapi.py b/spiderfoot/modules/sfp_nameapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..312bbb91e8a48543446ffffae36aa48f765cb38a
--- /dev/null
+++ b/spiderfoot/modules/sfp_nameapi.py
@@ -0,0 +1,129 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_nameapi
+# Purpose: Spiderfoot plugin to check if an email is
+# disposable using nameapi.org API.
+#
+# Author: Krishnasis Mandal
+#
+# Created: 2020-10-02
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_nameapi(SpiderFootPlugin):
+
+ meta = {
+ 'name': "NameAPI",
+ 'summary': "Check whether an email is disposable",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.nameapi.org/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://www.nameapi.org/en/developer/manuals/rest-web-services/53/web-services/disposable-email-address-detector/"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://nameapi.org",
+ "Click on 'Get API Key'",
+ "Register a free account",
+ "The API key will be sent to your email"
+ ],
+ 'favIcon': "https://www.nameapi.org/fileadmin/favicon.ico",
+ 'logo': "https://www.nameapi.org/fileadmin/templates/nameprofiler/images/name-api-logo.png",
+ 'description': "The NameAPI DEA-Detector checks email addresses "
+ "against a list of known trash domains such as mailinator.com.\n"
+ "It classifies those as disposable which operate as a time-limited, "
+ "web based way of receiving emails, for example, sign up confirmations.",
+ }
+ }
+
+ opts = {
+ 'api_key': ''
+ }
+
+ optdescs = {
+ 'api_key': "API Key for NameAPI"
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "EMAILADDR"
+ ]
+
+ def producedEvents(self):
+ return [
+ "EMAILADDR_DISPOSABLE",
+ "RAW_RIR_DATA"
+ ]
+
+ def queryEmailAddr(self, qry):
+ res = self.sf.fetchUrl(
+ f"http://api.nameapi.org/rest/v5.3/email/disposableemailaddressdetector?apiKey={self.opts['api_key']}&emailAddress={qry}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot"
+ )
+
+ if res['content'] is None:
+ self.info(f"No NameAPI info found for {qry}")
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from NameAPI: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!"
+ )
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ data = self.queryEmailAddr(eventData)
+
+ if data is None:
+ return
+
+ isDisposable = data.get('disposable')
+
+ if isDisposable == "YES":
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent("EMAILADDR_DISPOSABLE", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_nameapi class
diff --git a/spiderfoot/modules/sfp_names.py b/spiderfoot/modules/sfp_names.py
new file mode 100644
index 0000000000000000000000000000000000000000..038414ae523877ecd1e862466cbc124db108edbc
--- /dev/null
+++ b/spiderfoot/modules/sfp_names.py
@@ -0,0 +1,172 @@
+# coding: utf-8
+# -------------------------------------------------------------------------------
+# Name: sfp_names
+# Purpose: Identify human names in content fetched.
+#
+# Author: Steve Micallef
+#
+# Created: 24/03/2014
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_names(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Human Name Extractor",
+ 'summary': "Attempt to identify human names in fetched content.",
+ 'flags': ["errorprone"],
+ 'useCases': ["Footprint", "Passive"],
+ 'categories': ["Content Analysis"]
+ }
+
+ # Default options
+ opts = {
+ 'algolimit': 75,
+ 'emailtoname': True,
+ 'filterjscss': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'algolimit': "A value between 0-100 to tune the sensitivity of the name finder. Less than 40 will give you a lot of junk, over 50 and you'll probably miss things but will have less false positives.",
+ 'emailtoname': "Convert e-mail addresses in the form of firstname.surname@target to names?",
+ 'filterjscss': "Filter out names that originated from CSS/JS content. Enabling this avoids detection of popular Javascript and web framework author names."
+ }
+
+ results = None
+ d = None
+ n = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.d = SpiderFootHelpers.dictionaryWordsFromWordlists()
+ self.n = SpiderFootHelpers.humanNamesFromWordlists()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["TARGET_WEB_CONTENT", "EMAILADDR",
+ "DOMAIN_WHOIS", "NETBLOCK_WHOIS",
+ "RAW_RIR_DATA", "RAW_FILE_META_DATA"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["HUMAN_NAME"]
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ # If the source event is web content, check if the source URL was javascript
+ # or CSS, in which case optionally ignore it.
+ if eventName == "TARGET_WEB_CONTENT":
+ url = event.actualSource
+ if url is not None:
+ if self.opts['filterjscss'] and (".js" in url or ".css" in url):
+ self.debug("Ignoring web content from CSS/JS.")
+ return
+
+ # Find names in email addresses in ".@" format
+ if eventName == "EMAILADDR" and self.opts['emailtoname']:
+ potential_name = eventData.split("@")[0]
+
+ if "." not in potential_name:
+ return
+
+ name = " ".join(map(str.capitalize, potential_name.split(".")))
+
+ # Names usually do not contain numbers
+ if re.search("[0-9]", name):
+ return
+
+ evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+ return
+
+ # For RAW_RIR_DATA, there are only specific modules we
+ # expect to see RELEVANT names within.
+ if eventName == "RAW_RIR_DATA":
+ if srcModuleName not in ["sfp_builtwith", "sfp_clearbit", "sfp_emailcrawlr",
+ "sfp_fullcontact", "sfp_github", "sfp_hunter",
+ "sfp_opencorporates", "sfp_slideshare", "sfp_jsonwhoiscom",
+ "sfp_twitter", "sfp_gravatar", "sfp_keybase"]:
+ self.debug("Ignoring RAW_RIR_DATA from untrusted module.")
+ return
+
+ # Stage 1: Find things that look (very vaguely) like names
+ rx = re.compile(r"([A-Z][a-z�������������]+)\s+.?.?\s?([A-Z][�������������a-zA-Z\'\-]+)")
+ m = re.findall(rx, eventData)
+ for r in m:
+ # Start off each match as 0 points.
+ p = 0
+ notindict = False
+
+ # Shouldn't encounter "Firstname's Secondname"
+ first = r[0].lower()
+ if first[len(first) - 2] == "'" or first[len(first) - 1] == "'":
+ continue
+
+ # Strip off trailing ' or 's
+ secondOrig = r[1].replace("'s", "")
+ secondOrig = secondOrig.rstrip("'")
+ second = r[1].lower().replace("'s", "")
+ second = second.rstrip("'")
+
+ # If both words are not in the dictionary, add 75 points.
+ if first not in self.d and second not in self.d:
+ self.debug(f"Both first and second names are not in the dictionary, so high chance of name: ({first}:{second}).")
+ p += 75
+ notindict = True
+ else:
+ self.debug(first + " was found or " + second + " was found in dictionary.")
+
+ # If the first word is a known popular first name, award 50 points.
+ if first in self.n:
+ p += 50
+
+ # If either word is 2 characters, subtract 50 points.
+ if len(first) == 2 or len(second) == 2:
+ p -= 50
+
+ # If the first word is in the dictionary but the second isn't,
+ # subtract 40 points.
+ if not notindict:
+ if first in self.d and second not in self.d:
+ p -= 20
+
+ # If the second word is in the dictionary but the first isn't,
+ # reduce 20 points.
+ if first not in self.d and second in self.d:
+ p -= 40
+
+ name = r[0] + " " + secondOrig
+
+ self.debug("Name of " + name + " has score: " + str(p))
+ if p >= self.opts['algolimit']:
+ # Notify other modules of what you've found
+ evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)
+ if event.moduleDataSource:
+ evt.moduleDataSource = event.moduleDataSource
+ else:
+ evt.moduleDataSource = "Unknown"
+ self.notifyListeners(evt)
+
+
+# End of sfp_names class
diff --git a/spiderfoot/modules/sfp_networksdb.py b/spiderfoot/modules/sfp_networksdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a073470f40e13bfc5e0caa3d561c191dfd3868f
--- /dev/null
+++ b/spiderfoot/modules/sfp_networksdb.py
@@ -0,0 +1,371 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_networksdb
+# Purpose: SpiderFoot plug-in to search NetworksDB.io API for IP address and
+# domain information.
+#
+# Author:
+#
+# Created: 2019-09-16
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_networksdb(SpiderFootPlugin):
+
+ meta = {
+ 'name': "NetworksDB",
+ 'summary': "Search NetworksDB.io API for IP address and domain information.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Passive DNS"],
+ 'dataSource': {
+ 'website': "https://networksdb.io/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://networksdb.io/api/docs"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://networksdb.io/api/order/free",
+ "Register a free account",
+ "Click on 'Generate a Free API Key'",
+ "The API key is listed under 'API Key: Free plan'"
+ ],
+ 'favIcon': "https://networksdb.io/img/favicon/favicon-96x96.png",
+ 'logo': "https://networksdb.io/img/logo.png",
+ 'description': "Our database contains information about the public IPv4 and IPv6 addresses, "
+ "networks and domains owned by companies and organisations across the world "
+ "along with city-level IP geolocation data and autonomous system information.",
+ }
+ }
+ # Default options
+ opts = {
+ 'api_key': '',
+ 'delay': 1,
+ 'verify': True,
+ 'cohostsamedomain': False,
+ 'maxcohost': 100
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': 'NetworksDB API key.',
+ 'delay': 'Delay between requests, in seconds.',
+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",
+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",
+ 'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting."
+ }
+
+ cohostcount = 0
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.cohostcount = 0
+ self.errorState = False
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "IPV6_ADDRESS", "INTERNET_NAME", "DOMAIN_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["INTERNET_NAME", "IP_ADDRESS", "IPV6_ADDRESS", "NETBLOCK_MEMBER",
+ "CO_HOSTED_SITE", "GEOINFO", "RAW_RIR_DATA"]
+
+ # Query IP Address Info
+ # https://networksdb.io/api/docs#ipinfo
+ def queryIpInfo(self, qry):
+ params = {
+ 'ip': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/ip-info',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query IP Geolocation
+ # https://networksdb.io/api/docs#geoip
+ def queryIpGeo(self, qry):
+ params = {
+ 'ip': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/ip-geo',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query Domains on IP (Reverse DNS)
+ # https://networksdb.io/api/docs#revdns
+ def queryReverseDns(self, qry):
+ params = {
+ 'ip': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/reverse-dns',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query IPs for Domain (Forward DNS)
+ # https://networksdb.io/api/docs#fwddns
+ def queryForwardDns(self, qry):
+ params = {
+ 'domain': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/dns',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query Autonomous System Info
+ # https://networksdb.io/api/docs#asinfo
+ # Note: currently unused
+ def queryAsnInfo(self, qry):
+ params = {
+ 'asn': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/asn',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Query Autonomous System Networks
+ # https://networksdb.io/api/docs#asnets
+ # Note: currently unused
+ def queryAsnNetworks(self, qry):
+ params = {
+ 'asn': qry,
+ }
+ headers = {
+ 'Accept': 'application/json',
+ 'X-Api-Key': self.opts['api_key'],
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ }
+ res = self.sf.fetchUrl('https://networksdb.io/api/asn-networks',
+ headers=headers,
+ postData=urllib.parse.urlencode(params),
+ timeout=15,
+ useragent=self.opts['_useragent'])
+
+ time.sleep(self.opts['delay'])
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ # https://networksdb.io/api/plans
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from NetworksDB.")
+ return None
+
+ # Future proofing - NetworksDB does not implement rate limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by NetworksDB")
+ self.errorState = True
+ return None
+
+ if res['code'] == '403':
+ self.error("Authentication failed")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.error(f"Error processing JSON response from NetworksDB: {e}")
+ return None
+
+ if data.get('warning'):
+ self.debug("Received warning from NetworksDB: " + data.get('warning'))
+
+ if data.get('error'):
+ self.error("Received error from NetworksDB: " + data.get('error'))
+
+ return data
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if eventData in self.results:
+ return
+
+ if self.opts['api_key'] == '':
+ self.error("You enabled sfp_networksdb but did not set an API key!")
+ self.errorState = True
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventName in ["IP_ADDRESS", "IPV6_ADDRESS"]:
+ data = self.queryIpInfo(eventData)
+
+ if data is None:
+ self.debug("No IP address information found for " + eventData)
+ else:
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ network = data.get('network')
+ if network:
+ cidr = network.get('cidr')
+ if cidr and cidr != 'N/A' and self.sf.validIpNetwork(cidr):
+ if ":" in cidr:
+ evt = SpiderFootEvent('NETBLOCKV6_MEMBER', cidr, self.__name__, event)
+ else:
+ evt = SpiderFootEvent('NETBLOCK_MEMBER', cidr, self.__name__, event)
+ self.notifyListeners(evt)
+
+ data = self.queryIpGeo(eventData)
+
+ if data is None:
+ self.debug("No IP geolocation information found for " + eventData)
+ else:
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('country'):
+ location = ', '.join(filter(None, [data.get('city'), data.get('state'), data.get('country')]))
+ evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ data = self.queryReverseDns(eventData)
+
+ cohosts = list()
+
+ if data is None:
+ self.debug("No reverse DNS results for " + eventData)
+ else:
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ results = data.get('results')
+ if results:
+ for domain in results:
+ cohosts.append(domain)
+
+ for co in set(cohosts):
+ if self.checkForStop():
+ return
+
+ if co in self.results:
+ continue
+
+ if self.opts['verify'] and not self.sf.validateIP(co, eventData):
+ self.debug("Host " + co + " no longer resolves to " + eventData)
+ continue
+
+ if not self.opts['cohostsamedomain']:
+ if self.getTarget().matches(co, includeParents=True):
+ evt = SpiderFootEvent('INTERNET_NAME', co, self.__name__, event)
+ self.notifyListeners(evt)
+ if self.sf.isDomain(co, self.opts['_internettlds']):
+ evt = SpiderFootEvent('DOMAIN_NAME', co, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ evt = SpiderFootEvent('CO_HOSTED_SITE', co, self.__name__, event)
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+
+ if eventName in ["INTERNET_NAME", "DOMAIN_NAME"]:
+ data = self.queryForwardDns(eventData)
+
+ if data is None:
+ self.debug("No forward DNS results for " + eventData)
+ return
+
+ res = data.get('results')
+
+ if not res:
+ self.debug("No forward DNS results for " + eventData)
+ return
+
+ evt = SpiderFootEvent('RAW_RIR_DATA', str(res), self.__name__, event)
+ self.notifyListeners(evt)
+
+ for ip in res:
+ if self.sf.validIP(ip):
+ evt = SpiderFootEvent('IP_ADDRESS', ip, self.__name__, event)
+ self.notifyListeners(evt)
+ elif self.sf.validIP6(ip):
+ evt = SpiderFootEvent('IPV6_ADDRESS', ip, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_networksdb class
diff --git a/spiderfoot/modules/sfp_neutrinoapi.py b/spiderfoot/modules/sfp_neutrinoapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..9baf03e3186306a65e72146586e94709fbbdf3c6
--- /dev/null
+++ b/spiderfoot/modules/sfp_neutrinoapi.py
@@ -0,0 +1,262 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_neutrinoapi
+# Purpose: SpiderFoot plug-in to search NeutrinoAPI for IP address info,
+# check IP address reputation, and search for phone location.
+#
+# Author:
+#
+# Created: 2018-11-30
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_neutrinoapi(SpiderFootPlugin):
+
+ meta = {
+ 'name': "NeutrinoAPI",
+ 'summary': "Search NeutrinoAPI for phone location information, IP address information, and host reputation.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.neutrinoapi.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://www.neutrinoapi.com/api/api-basics/",
+ "https://www.neutrinoapi.com/api/phone-validate/",
+ "https://www.neutrinoapi.com/api/ip-info/",
+ "https://www.neutrinoapi.com/api/ip-blocklist/",
+ "https://www.neutrinoapi.com/api/host-reputation/",
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://www.neutrinoapi.com/",
+ "Sign up for a free account",
+ "Click on 'My Account'",
+ "The API key is listed under 'Master Key'"
+ ],
+ 'favIcon': "https://www.neutrinoapi.com/favicon.png",
+ 'logo': "https://www.neutrinoapi.com/favicon.png",
+ 'description': "Neutrino API - The general-purpose API - Build smarter applications."
+ }
+ }
+
+ # Default options
+ opts = {
+ 'user_id': '',
+ 'api_key': '',
+ 'timeout': 30
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'user_id': "NeutrinoAPI user ID.",
+ 'api_key': "NeutrinoAPI API key.",
+ 'timeout': "Query timeout, in seconds."
+ }
+
+ results = None
+ errorState = False
+
+ # Initialize module and module options
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.__dataSource__ = "NeutrinoAPI"
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS', 'IPV6_ADDRESS', 'PHONE_NUMBER']
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ 'RAW_RIR_DATA',
+ 'BLACKLISTED_IPADDR',
+ 'MALICIOUS_IPADDR',
+ 'PROXY_HOST',
+ 'VPN_HOST',
+ 'TOR_EXIT_NODE',
+ 'GEOINFO',
+ ]
+
+ # Query the phone-validate REST API
+ # https://www.neutrinoapi.com/api/phone-validate/
+ def queryPhoneValidate(self, qry):
+ res = self.sf.fetchUrl(
+ 'https://neutrinoapi.com/phone-validate',
+ postData={"output-format": "json", "number": qry, "user-id": self.opts['user_id'], "api-key": self.opts['api_key']},
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ return self.parseApiResponse(res)
+
+ # Query the ip-info REST API
+ # https://www.neutrinoapi.com/api/ip-info/
+ def queryIpInfo(self, qry):
+ res = self.sf.fetchUrl(
+ "https://neutrinoapi.com/ip-info",
+ postData={"output-format": "json", "ip": qry, "user-id": self.opts['user_id'], "api-key": self.opts['api_key']},
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ return self.parseApiResponse(res)
+
+ # Query the ip-blocklist REST API
+ # https://www.neutrinoapi.com/api/ip-blocklist/
+ def queryIpBlocklist(self, qry):
+ res = self.sf.fetchUrl(
+ "https://neutrinoapi.com/ip-blocklist",
+ postData={"output-format": "json", "ip": qry, "vpn-lookup": True, "user-id": self.opts['user_id'], "api-key": self.opts['api_key']},
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ return self.parseApiResponse(res)
+
+ # Query the host-reputation REST API
+ # https://www.neutrinoapi.com/api/host-reputation/
+ def queryHostReputation(self, qry):
+ res = self.sf.fetchUrl(
+ "https://neutrinoapi.com/host-reputation",
+ postData={"output-format": "json", "host": qry, "user-id": self.opts['user_id'], "api-key": self.opts['api_key']},
+ timeout=self.opts['timeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ return self.parseApiResponse(res)
+
+ # Parse API response
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from NeutrinoAPI.")
+ return None
+
+ if res['code'] == "403":
+ self.error("Authentication failed")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if res['code'] == "400":
+ if data.get('api-error-msg'):
+ self.error("Error: " + data.get('api-error-msg'))
+ if "EXCEED" in data.get('api-error-msg'):
+ self.errorState = True
+ return None
+ else:
+ self.error("Error: HTTP 400")
+ return None
+
+ return data
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_neutrinoapi but did not set an API key!")
+ self.errorState = True
+ return
+
+ if self.opts['user_id'] == "":
+ self.error("You enabled sfp_neutrinoapi but did not set a user ID!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == 'PHONE_NUMBER':
+ data = self.queryPhoneValidate(eventData)
+
+ if data is None:
+ self.debug("No phone info results found for " + eventData)
+ else:
+ if data.get('location') is not None and data.get('country') is not None:
+ if data.get('location') == data.get('country'):
+ location = data.get('location')
+ else:
+ location = data.get('location') + ', ' + data.get('country')
+
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName in ['IP_ADDRESS', 'IPV6_ADDRESS']:
+ data = self.queryIpInfo(eventData)
+
+ if data is None:
+ self.debug("No IP info results found for " + eventData)
+ else:
+ if data.get('city') is not None and data.get('region') is not None and data.get('country-code') is not None:
+ location = data.get('city') + ', ' + data.get('region') + ', ' + data.get('country-code')
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ data = self.queryIpBlocklist(eventData)
+
+ if data is None:
+ self.debug("No IP blocklist results found for " + eventData)
+ else:
+ if data.get('is-listed'):
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", f"NeutrinoAPI - IP Blocklist [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent("BLACKLISTED_IPADDR", f"NeutrinoAPI - IP Blocklist [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('is-proxy'):
+ evt = SpiderFootEvent("PROXY_HOST", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('is-vpn'):
+ evt = SpiderFootEvent("VPN_HOST", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('is-tor'):
+ evt = SpiderFootEvent("TOR_EXIT_NODE", eventData, self.__name__, event)
+ self.notifyListeners(evt)
+
+ data = self.queryHostReputation(eventData)
+
+ if data is None:
+ self.debug("No host reputation results found for " + eventData)
+ else:
+ if data.get('is-listed'):
+ evt = SpiderFootEvent("MALICIOUS_IPADDR", f"NeutrinoAPI - Host Reputation [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent("BLACKLISTED_IPADDR", f"NeutrinoAPI - Host Reputation [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_neutrinoapi class
diff --git a/spiderfoot/modules/sfp_numverify.py b/spiderfoot/modules/sfp_numverify.py
new file mode 100644
index 0000000000000000000000000000000000000000..a603b3dd8ac6f1be1b559ffe1b591d887ea8a57a
--- /dev/null
+++ b/spiderfoot/modules/sfp_numverify.py
@@ -0,0 +1,176 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_numverify
+# Purpose: SpiderFoot plug-in to search numverify.com API for a phone number
+# and retrieve location and carrier information.
+#
+# Author:
+#
+# Created: 2019-05-25
+# Copyright: (c) bcoles 2019
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
+
+
+class sfp_numverify(SpiderFootPlugin):
+
+ meta = {
+ 'name': "numverify",
+ 'summary': "Lookup phone number location and carrier information from numverify.com.",
+ 'flags': ["apikey"],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "http://numverify.com/",
+ 'model': "FREE_AUTH_LIMITED",
+ 'references': [
+ "https://numverify.com/documentation",
+ "https://numverify.com/faq"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://numverify.com",
+ "Sign up for a free account",
+ "Navigate to https://numverify.com/dashboard",
+ "The API key is listed under 'Your API Access Key'"
+ ],
+ 'favIcon': "https://numverify.com/images/icons/numverify_shortcut_icon.ico",
+ 'logo': "https://numverify.com/images/logos/numverify_header.png",
+ 'description': "Global Phone Number Validation & Lookup JSON API.\n"
+ "NumVerify offers a full-featured yet simple RESTful JSON API for "
+ "national and international phone number validation and information lookup for a total of 232 countries around the world.\n"
+ "Requested numbers are processed in real-time, cross-checked with the latest international numbering plan databases "
+ "and returned in handy JSON format enriched with useful carrier, geographical location and line type data.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'api_key': ''
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'api_key': 'numverify API key.'
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['PHONE_NUMBER']
+
+ # What events this module produces
+ def producedEvents(self):
+ return ['RAW_RIR_DATA', 'GEOINFO', 'PROVIDER_TELCO']
+
+ # Query numverify API for the specified phone number
+ # https://numverify.com/documentation
+ def query(self, qry):
+ number = qry.strip('+').strip('(').strip(')')
+
+ params = {
+ 'number': number.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'country_code': '',
+ 'format': '0', # set to "1" for prettified debug output
+ 'access_key': self.opts['api_key']
+ }
+
+ # Free API does not support HTTPS for no adequately explained reason
+ res = self.sf.fetchUrl("http://apilayer.net/api/validate?" + urllib.parse.urlencode(params),
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+
+ time.sleep(1)
+
+ if res['content'] is None:
+ self.debug('No response from apilayer.net')
+ return None
+
+ if res['code'] == '101':
+ self.error('API error: invalid API key')
+ self.errorState = True
+ return None
+
+ if res['code'] == '102':
+ self.error('API error: user account deactivated')
+ self.errorState = True
+ return None
+
+ if res['code'] == '104':
+ self.error('API error: usage limit exceeded')
+ self.errorState = True
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if data.get('error') is not None:
+ self.error('API error: ' + str(data.get('error')))
+ return None
+
+ return data
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_numverify but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ data = self.query(eventData)
+
+ if data is None:
+ self.debug("No phone information found for " + eventData)
+ return
+
+ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
+ self.notifyListeners(evt)
+
+ if data.get('country_code'):
+ country = SpiderFootHelpers.countryNameFromCountryCode(data.get('country_code'))
+ location = ', '.join([_f for _f in [data.get('location'), country] if _f])
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ self.debug("No location information found for " + eventData)
+
+ if data.get('carrier'):
+ evt = SpiderFootEvent("PROVIDER_TELCO", data.get('carrier'), self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ self.debug("No carrier information found for " + eventData)
+
+# End of sfp_numverify class
diff --git a/spiderfoot/modules/sfp_onioncity.py b/spiderfoot/modules/sfp_onioncity.py
new file mode 100644
index 0000000000000000000000000000000000000000..33f537c9e29e1ed2e4ebdcb2400b6493ff492aa0
--- /dev/null
+++ b/spiderfoot/modules/sfp_onioncity.py
@@ -0,0 +1,191 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_onioncity
+# Purpose: Searches the Tor search engine 'Onion City' using Google Custom
+# Search for content related to the domain in question.
+#
+# Author: Steve Micallef
+#
+# Created: 15/07/2015
+# Copyright: (c) Steve Micallef 2015
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_onioncity(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Onion.link",
+ 'summary': "Search Tor 'Onion City' search engine for mentions of the target domain using Google Custom Search.",
+ 'flags': ["apikey", "tor"],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://onion.link/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://developers.google.com/custom-search/v1",
+ "https://developers.google.com/custom-search/docs/overview",
+ "https://cse.google.com/cse"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://developers.google.com/custom-search/v1/introduction",
+ "Register a free Google account",
+ "Click on 'Get A Key'",
+ "Connect a Project",
+ "The API Key will be listed under 'YOUR API KEY'"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://onion.link",
+ 'logo': "https://onion.link/images/OC.png",
+ 'description': "Enabling search and global access to Tor's onionsites.",
+ }
+ }
+
+ # Default options
+ opts = {
+ "api_key": "",
+ "cse_id": "013611106330597893267:tfgl3wxdtbp",
+ 'fetchlinks': True,
+ 'fullnames': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ "api_key": "Google API Key for Onion.link search.",
+ "cse_id": "Google Custom Search Engine ID.",
+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target.",
+ 'fullnames': "Search for human names?"
+ }
+
+ # Target
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME", "DOMAIN_NAME"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["DARKNET_MENTION_URL", "DARKNET_MENTION_CONTENT",
+ "RAW_RIR_DATA"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if self.errorState:
+ return
+
+ if not self.opts['fullnames'] and eventName == 'HUMAN_NAME':
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == "":
+ self.error("You enabled sfp_onioncity but did not set a Google API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug(f"Already did a search for {eventData}, skipping.")
+ return
+
+ self.results[eventData] = True
+
+ # Sites hosted on the domain
+ res = self.sf.googleIterate(
+ searchString="+site:onion.link " + eventData,
+ opts={
+ "timeout": self.opts["_fetchtimeout"],
+ "useragent": self.opts["_useragent"],
+ "api_key": self.opts["api_key"],
+ "cse_id": self.opts["cse_id"],
+ },
+ )
+ if res is None:
+ # Failed to talk to the bing API or no results returned
+ return
+
+ urls = res["urls"]
+ new_links = list(set(urls) - set(self.results.keys()))
+
+ # Add new links to results
+ for link in new_links:
+ self.results[link] = True
+
+ # Submit the Google results for analysis
+ googlesearch_url = res["webSearchUrl"]
+ response = self.sf.fetchUrl(
+ googlesearch_url,
+ timeout=self.opts["_fetchtimeout"],
+ useragent=self.opts["_useragent"],
+ )
+ if response['code'] in ["200", "201", "202"]:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", response["content"], self.__name__, event
+ )
+ self.notifyListeners(evt)
+ else:
+ self.error("Failed to fetch Google web search URL")
+
+ # Check if we've been asked to stop
+ if self.checkForStop():
+ return
+
+ darknet_links = [
+ link for link in new_links if self.sf.urlFQDN(link).endswith(".onion.link")
+ ]
+
+ for link in darknet_links:
+ self.debug("Found a darknet mention: " + link)
+ torlink = link.replace(".onion.link", ".onion")
+ if self.opts['fetchlinks']:
+ res = self.sf.fetchUrl(torlink, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False)
+
+ if res['content'] is None:
+ self.debug("Ignoring " + link + " as no data returned")
+ continue
+
+ # Sometimes onion city search results false positives
+ if re.search(r"[^a-zA-Z\-\_0-9]" + re.escape(eventData)
+ + r"[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:
+ self.debug("Ignoring " + link + " as no mention of " + eventData)
+ continue
+
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)
+ self.notifyListeners(evt)
+
+ try:
+ startIndex = res['content'].index(eventData) - 120
+ endIndex = startIndex + len(eventData) + 240
+ except Exception:
+ self.debug("String not found in content.")
+ continue
+
+ data = res['content'][startIndex:endIndex]
+ evt = SpiderFootEvent("DARKNET_MENTION_CONTENT", "..." + data + "...",
+ self.__name__, evt)
+ self.notifyListeners(evt)
+ else:
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_onioncity class
diff --git a/spiderfoot/modules/sfp_onionsearchengine.py b/spiderfoot/modules/sfp_onionsearchengine.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e92397bdcab171d16771b371f55d6020d77c0db
--- /dev/null
+++ b/spiderfoot/modules/sfp_onionsearchengine.py
@@ -0,0 +1,185 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_onionsearchengine
+# Purpose: Searches the Tor search engine onionsearchengine.com for content
+# related to the domain in question.
+#
+# Author: Steve Micallef
+#
+# Created: 27/10/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_onionsearchengine(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Onionsearchengine.com",
+ 'summary': "Search Tor onionsearchengine.com for mentions of the target domain.",
+ 'flags': ["tor"],
+ 'useCases': ["Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://as.onionsearchengine.com",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://helpdesk.onionsearchengine.com/?v=knowledgebase",
+ "https://onionsearchengine.com/add_url.php"
+ ],
+ 'favIcon': "https://as.onionsearchengine.com/images/onionsearchengine.jpg",
+ 'logo': "https://as.onionsearchengine.com/images/onionsearchengine.jpg",
+ 'description': "No cookies, no javascript, no trace. We protect your privacy.\n"
+ "Onion search engine is search engine with ability to find content on tor network / deepweb / darkweb.",
+ }
+ }
+
+ # Default options
+ opts = {
+ 'timeout': 10,
+ 'max_pages': 20,
+ 'fetchlinks': True,
+ 'blacklist': ['.*://relate.*'],
+ 'fullnames': True
+ }
+
+ # Option descriptions
+ optdescs = {
+ 'timeout': "Query timeout, in seconds.",
+ 'max_pages': "Maximum number of pages of results to fetch.",
+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target.",
+ 'blacklist': "Exclude results from sites matching these patterns.",
+ 'fullnames': "Search for human names?"
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["DOMAIN_NAME", "HUMAN_NAME", "EMAILADDR"]
+
+ # What events this module produces
+ # This is to support the end user in selecting modules based on events
+ # produced.
+ def producedEvents(self):
+ return ["DARKNET_MENTION_URL", "DARKNET_MENTION_CONTENT"]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ if not self.opts['fullnames'] and eventName == 'HUMAN_NAME':
+ return
+
+ if eventData in self.results:
+ self.debug("Already did a search for " + eventData + ", skipping.")
+ return
+
+ self.results[eventData] = True
+
+ keepGoing = True
+ page = 1
+ while keepGoing and page <= int(self.opts['max_pages']):
+ # Check if we've been asked to stop
+ if self.checkForStop():
+ return
+
+ params = {
+ 'search': '"' + eventData.encode('raw_unicode_escape').decode("ascii", errors='replace') + '"',
+ 'submit': 'Search',
+ 'page': str(page)
+ }
+
+ # Sites hosted on the domain
+ data = self.sf.fetchUrl('https://onionsearchengine.com/search.php?' + urllib.parse.urlencode(params),
+ useragent=self.opts['_useragent'],
+ timeout=self.opts['timeout'])
+
+ if data is None or not data.get('content'):
+ self.info("No results returned from onionsearchengine.com.")
+ return
+
+ page += 1
+
+ if "url.php?u=" not in data['content']:
+ # Work around some kind of bug in the site
+ if "you didn't submit a keyword" in data['content']:
+ continue
+ return
+
+ if "forward >" not in data['content']:
+ keepGoing = False
+
+ links = re.findall(r"url\.php\?u=(.[^\"\']+)[\"\']",
+ data['content'], re.IGNORECASE | re.DOTALL)
+
+ for link in links:
+ if self.checkForStop():
+ return
+
+ if link in self.results:
+ continue
+
+ self.results[link] = True
+
+ blacklist = False
+ for r in self.opts['blacklist']:
+ if re.match(r, link, re.IGNORECASE):
+ self.debug("Skipping " + link + " as it matches blacklist " + r)
+ blacklist = True
+ if blacklist:
+ continue
+
+ self.debug("Found a darknet mention: " + link)
+
+ if not self.sf.urlFQDN(link).endswith(".onion"):
+ continue
+
+ if not self.opts['fetchlinks']:
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ res = self.sf.fetchUrl(link,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ verify=False)
+
+ if res['content'] is None:
+ self.debug("Ignoring " + link + " as no data returned")
+ continue
+
+ if eventData not in res['content']:
+ self.debug("Ignoring " + link + " as no mention of " + eventData)
+ continue
+
+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)
+ self.notifyListeners(evt)
+
+ try:
+ startIndex = res['content'].index(eventData) - 120
+ endIndex = startIndex + len(eventData) + 240
+ except Exception:
+ self.debug('String "' + eventData + '" not found in content.')
+ continue
+
+ data = res['content'][startIndex:endIndex]
+ evt = SpiderFootEvent("DARKNET_MENTION_CONTENT", "..." + data + "...",
+ self.__name__, evt)
+ self.notifyListeners(evt)
+
+# End of sfp_onionsearchengine class
diff --git a/spiderfoot/modules/sfp_onyphe.py b/spiderfoot/modules/sfp_onyphe.py
new file mode 100644
index 0000000000000000000000000000000000000000..001785905ccfbf600c17b00d194b9e7060a329e8
--- /dev/null
+++ b/spiderfoot/modules/sfp_onyphe.py
@@ -0,0 +1,420 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_onyphe
+# Purpose: SpiderFoot plug-in to check if the IP is included on Onyphe
+# data (threat list, geo-location, pastries, vulnerabilities)
+#
+# Author: Filip Aleksić
+#
+# Created: 2020-08-21
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import time
+from datetime import datetime
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_onyphe(SpiderFootPlugin):
+
+ meta = {
+ "name": "Onyphe",
+ "summary": "Check Onyphe data (threat list, geo-location, pastries, vulnerabilities) about a given IP.",
+ 'flags': ["apikey"],
+ "useCases": ["Footprint", "Passive", "Investigate"],
+ "categories": ["Reputation Systems"],
+ "dataSource": {
+ "website": "https://www.onyphe.io",
+ "model": "FREE_AUTH_LIMITED",
+ "references": ["https://www.onyphe.io/documentation/api"],
+ "apiKeyInstructions": [
+ "Visit https://www.onyphe.io/login/#register",
+ "Register a free account",
+ "You should receive your API key on your email, or you can get it by yourself following next steps",
+ "Go to your account settings https://www.onyphe.io/auth/account",
+ "The API key is listed under 'API Key'",
+ ],
+ "favIcon": "https://www.onyphe.io/favicon.ico",
+ "logo": "https://www.onyphe.io/img/logo-solo.png",
+ "description": "ONYPHE is a search engine for open-source "
+ "and cyber threat intelligence data collected by crawling "
+ "various sources available on the Internet or by listening "
+ "to Internet background noise. They make this data available "
+ "through API that we use. We check their data to see following "
+ "information about the IP: geo-location, does it have some "
+ "vulnerabilities, is it on some pastries (PasteBin) and "
+ "is it on their threat list",
+ },
+ }
+
+ opts = {
+ "api_key": "",
+ "paid_plan": False,
+ "max_page": 10,
+ "verify": True,
+ "age_limit_days": 30,
+ "cohostsamedomain": False,
+ "maxcohost": 100,
+ }
+ optdescs = {
+ "api_key": "Onyphe access token.",
+ "paid_plan": "Are you using paid plan? Paid plan has pagination enabled",
+ "max_page": "Maximum number of pages to iterate through. Onyphe has a maximum of 1000 pages (10,000 results). Only matters for paid plans",
+ "verify": "Verify identified domains still resolve to the associated specified IP address.",
+ "age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",
+ "maxcohost": "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",
+ "cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",
+ }
+
+ results = None
+ errorState = False
+ cohostcount = 0
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["IP_ADDRESS", "IPV6_ADDRESS"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return [
+ "GEOINFO",
+ "MALICIOUS_IPADDR",
+ "LEAKSITE_CONTENT",
+ "VULNERABILITY_CVE_CRITICAL",
+ "VULNERABILITY_CVE_HIGH",
+ "VULNERABILITY_CVE_MEDIUM",
+ "VULNERABILITY_CVE_LOW",
+ "VULNERABILITY_GENERAL",
+ "RAW_RIR_DATA",
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "PHYSICAL_COORDINATES",
+ ]
+
+ def query(self, endpoint, ip, page=1):
+ retarr = list()
+
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": f"apikey {self.opts['api_key']}",
+ }
+ res = self.sf.fetchUrl(
+ f"https://www.onyphe.io/api/v2/simple/{endpoint}/{ip}?page={page}",
+ timeout=self.opts["_fetchtimeout"],
+ useragent=self.opts["_useragent"],
+ headers=headers,
+ )
+
+ if res["code"] == "429":
+ self.error("Reaching rate limit on Onyphe API")
+ self.errorState = True
+ return None
+
+ if res["code"] == 400:
+ self.error("Invalid request or API key on Onyphe")
+ self.errorState = True
+ return None
+
+ try:
+ info = json.loads(res["content"])
+ if "status" in info and info["status"] == "nok":
+ self.error(
+ f"Unexpected error happened while requesting data from Onyphe. Error message: {info.get('text', '')}"
+ )
+ self.errorState = True
+ return None
+
+ if "results" not in info or info["results"] == []:
+ self.info(f"No Onyphe {endpoint} data found for {ip}")
+ return None
+ except Exception as e:
+ self.debug(f"{e.__class__} {res['code']} {res['content']}")
+ self.error("Error processing JSON response from Onyphe.")
+ return None
+
+ # Go through other pages if user has paid plan
+ try:
+ current_page = int(info["page"])
+ if (
+ self.opts["paid_plan"]
+ and info.get("page")
+ and int(info.get("max_page")) > current_page
+ ):
+ page = current_page + 1
+
+ if page > self.opts["max_page"]:
+ self.error(
+ "Maximum number of pages from options for Onyphe reached."
+ )
+ return [info]
+ retarr.append(info)
+ response = self.query(endpoint, ip, page)
+ if response:
+ retarr.extend(response)
+ else:
+ retarr.append(info)
+
+ except ValueError:
+ self.error(
+ f"Unexpected value for page in response from Onyphe, url: https://www.onyphe.io/api/v2/simple/{endpoint}/{ip}?page={page}"
+ )
+ self.errorState = True
+ return None
+
+ return retarr
+
+ def emitLocationEvent(self, location, eventData, event):
+ if location is None:
+ return
+ self.info(f"Found location for {eventData}: {location}")
+
+ evt = SpiderFootEvent("PHYSICAL_COORDINATES", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ def emitDomainData(self, response, eventData, event):
+ domains = set()
+ if response.get("domain") is not None and isinstance(
+ response['domain'], list
+ ):
+ for dom in response['domain']:
+ domains.add(dom)
+
+ if response.get("subdomains") is not None and isinstance(
+ response["subdomains"], list
+ ):
+ for subDomain in response["subdomains"]:
+ domains.add(subDomain)
+
+ for domain in domains:
+ if self.getTarget().matches(domain):
+ if self.opts['verify']:
+ if self.sf.resolveHost(domain) or self.sf.resolveHost6(domain):
+ evt = SpiderFootEvent('INTERNET_NAME', domain, self.__name__, event)
+ else:
+ evt = SpiderFootEvent('INTERNET_NAME_UNRESOLVED', domain, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if self.sf.isDomain(domain, self.opts['_internettlds']):
+ evt = SpiderFootEvent('DOMAIN_NAME', domain, self.__name__, event)
+ self.notifyListeners(evt)
+ continue
+
+ if self.cohostcount < self.opts['maxcohost']:
+ if self.opts["verify"] and not self.sf.validateIP(domain, eventData):
+ self.debug("Host no longer resolves to our IP.")
+ continue
+
+ if not self.opts["cohostsamedomain"] and self.getTarget().matches(domain, includeParents=True):
+ self.debug(f"Skipping {domain} because it is on the same domain.")
+ continue
+
+ evt = SpiderFootEvent("CO_HOSTED_SITE", domain, self.__name__, event)
+ self.notifyListeners(evt)
+ self.cohostcount += 1
+
+ def isFreshEnough(self, result):
+ limit = self.opts["age_limit_days"]
+ if limit <= 0:
+ return True
+
+ timestamp = result.get("@timestamp")
+ if timestamp is None:
+ self.debug("Record doesn't have timestamp defined")
+ return False
+
+ last_dt = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
+ last_ts = int(time.mktime(last_dt.timetuple()))
+ age_limit_ts = int(time.time()) - (86400 * limit)
+
+ if last_ts < age_limit_ts:
+ self.debug("Record found but too old, skipping.")
+ return False
+
+ return True
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ sentData = set()
+
+ if self.errorState:
+ return
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts["api_key"] == "":
+ self.error("You enabled sfp_onyphe, but did not set an API key!")
+ self.errorState = True
+ return
+
+ if eventData in self.results:
+ self.debug("Skipping " + eventData + " as already mapped.")
+ return
+
+ self.results[eventData] = True
+
+ geoLocDataArr = self.query("geoloc", eventData)
+
+ if geoLocDataArr is not None:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(geoLocDataArr), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+ for geoLocData in geoLocDataArr:
+ if self.checkForStop():
+ return
+
+ for result in geoLocData["results"]:
+ if not self.isFreshEnough(result):
+ continue
+
+ location = ", ".join(
+ [
+ _f
+ for _f in [
+ result.get("city"),
+ result.get("country"),
+ ]
+ if _f
+ ]
+ )
+ self.info("Found GeoIP for " + eventData + ": " + location)
+
+ if location in sentData:
+ self.debug(f"Skipping {location}, already sent")
+ continue
+
+ sentData.add(location)
+
+ evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
+ self.notifyListeners(evt)
+
+ coordinates = result.get("location")
+ if coordinates is None:
+ continue
+
+ if coordinates in sentData:
+ self.debug(f"Skipping {coordinates}, already sent")
+ continue
+ sentData.add(coordinates)
+
+ self.emitLocationEvent(coordinates, eventData, event)
+
+ self.emitDomainData(result, eventData, event)
+
+ pastriesDataArr = self.query("pastries", eventData)
+
+ if pastriesDataArr is not None:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(pastriesDataArr), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+ for pastriesData in pastriesDataArr:
+ if self.checkForStop():
+ return
+
+ for result in pastriesData["results"]:
+ pastry = result.get("content")
+ if pastry is None:
+ continue
+
+ if pastry in sentData:
+ self.debug(f"Skipping {pastry}, already sent")
+ continue
+ sentData.add(pastry)
+
+ if not self.isFreshEnough(result):
+ continue
+
+ evt = SpiderFootEvent(
+ "LEAKSITE_CONTENT", pastry, self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+ threatListDataArr = self.query("threatlist", eventData)
+
+ if threatListDataArr is not None:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(threatListDataArr), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+ for threatListData in threatListDataArr:
+ if self.checkForStop():
+ return
+
+ for result in threatListData["results"]:
+ threatList = result.get("threatlist")
+
+ if threatList is None:
+ continue
+
+ if threatList in sentData:
+ self.debug(f"Skipping {threatList}, already sent")
+ continue
+ sentData.add(threatList)
+
+ if not self.isFreshEnough(result):
+ continue
+
+ evt = SpiderFootEvent(
+ "MALICIOUS_IPADDR",
+ result.get("threatlist"),
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+
+ vulnerabilityDataArr = self.query("vulnscan", eventData)
+
+ if vulnerabilityDataArr is not None:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA", str(vulnerabilityDataArr), self.__name__, event
+ )
+ self.notifyListeners(evt)
+
+ for vulnerabilityData in vulnerabilityDataArr:
+ if self.checkForStop():
+ return
+
+ for result in vulnerabilityData["results"]:
+ if not self.isFreshEnough(result):
+ continue
+
+ cves = result.get("cve")
+
+ if cves is None:
+ continue
+
+ for cve in cves:
+ if not cve:
+ continue
+
+ if cve in sentData:
+ continue
+ sentData.add(cve)
+
+ etype, cvetext = self.sf.cveInfo(cve)
+ evt = SpiderFootEvent(
+ etype,
+ cvetext,
+ self.__name__,
+ event,
+ )
+ self.notifyListeners(evt)
+
+# End of sfp_onyphe class
diff --git a/spiderfoot/modules/sfp_openbugbounty.py b/spiderfoot/modules/sfp_openbugbounty.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c640175d7e5f57f81ac1788f5b96ce109d6ed02
--- /dev/null
+++ b/spiderfoot/modules/sfp_openbugbounty.py
@@ -0,0 +1,120 @@
+# -------------------------------------------------------------------------------
+# Name: sfp_openbugbounty
+# Purpose: Query the Open Bug Bounty database to see if our target appears.
+#
+# Author: Steve Micallef
+#
+# Created: 04/10/2015
+# Copyright: (c) Steve Micallef
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_openbugbounty(SpiderFootPlugin):
+
+ meta = {
+ 'name': "Open Bug Bounty",
+ 'summary': "Check external vulnerability scanning/reporting service openbugbounty.org to see if the target is listed.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Leaks, Dumps and Breaches"],
+ 'dataSource': {
+ 'website': "https://www.openbugbounty.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.openbugbounty.org/cert/"
+ ],
+ 'favIcon': "https://www.openbugbounty.org/favicon.ico",
+ 'logo': "https://www.openbugbounty.org/images/design/logo-obbnew.svg",
+ 'description': "Open Bug Bounty is an open, disintermediated, cost-free, and community-driven bug bounty platform "
+ "for coordinated, responsible and ISO 29147 compatible vulnerability disclosure.\n"
+ "The role of Open Bug Bounty is limited to independent verification of the "
+ "submitted vulnerabilities and proper notification of website owners by all available means. "
+ "Once notified, the website owner and the researcher are in direct contact to "
+ "remediate the vulnerability and coordinate its disclosure. "
+ "At this and at any later stages, we never act as an intermediary between "
+ "website owners and security researchers.",
+ }
+ }
+ # Default options
+ opts = {
+ }
+
+ # Option descriptions
+ optdescs = {
+ }
+
+ # Be sure to completely clear any class variables in setup()
+ # or you run the risk of data persisting between scan runs.
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ # Clear / reset any other class member variables here
+ # or you risk them persisting between threads.
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ["INTERNET_NAME"]
+
+ # What events this module produces
+ def producedEvents(self):
+ return ["VULNERABILITY_DISCLOSURE"]
+
+ # Query XSSposed.org
+ def queryOBB(self, qry):
+ ret = list()
+ base = "https://www.openbugbounty.org"
+ url = "https://www.openbugbounty.org/search/?search=" + qry
+ res = self.sf.fetchUrl(url, timeout=30, useragent=self.opts['_useragent'])
+
+ if res['content'] is None:
+ self.debug("No content returned from openbugbounty.org")
+ return None
+
+ try:
+ rx = re.compile(".*.*", re.IGNORECASE)
+ for m in rx.findall(str(res['content'])):
+ # Report it
+ if m[1] == qry or m[1].endswith("." + qry):
+ ret.append("From openbugbounty.org: " + base + m[0] + " ")
+ except Exception as e:
+ self.error("Error processing response from openbugbounty.org: " + str(e))
+ return None
+ return ret
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ data = list()
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ obb = self.queryOBB(eventData)
+ if obb:
+ data.extend(obb)
+
+ for n in data:
+ # Notify other modules of what you've found
+ e = SpiderFootEvent("VULNERABILITY_DISCLOSURE", n, self.__name__, event)
+ self.notifyListeners(e)
+
+# End of sfp_openbugbounty class
diff --git a/spiderfoot/modules/sfp_opencorporates.py b/spiderfoot/modules/sfp_opencorporates.py
new file mode 100644
index 0000000000000000000000000000000000000000..c053c3111ba705ed7db12103d01fcd4541937a74
--- /dev/null
+++ b/spiderfoot/modules/sfp_opencorporates.py
@@ -0,0 +1,258 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_opencorporates
+# Purpose: SpiderFoot plug-in for retrieving company information from
+# OpenCorporates.
+#
+# Author:
+#
+# Created: 2018-10-21
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import urllib
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_opencorporates(SpiderFootPlugin):
+
+ meta = {
+ 'name': "OpenCorporates",
+ 'summary': "Look up company information from OpenCorporates.",
+ 'flags': ["apikey"],
+ 'useCases': ["Passive", "Footprint", "Investigate"],
+ 'categories': ["Search Engines"],
+ 'dataSource': {
+ 'website': "https://opencorporates.com",
+ 'model': "FREE_NOAUTH_LIMITED",
+ 'references': [
+ "https://api.opencorporates.com/documentation/API-Reference"
+ ],
+ 'apiKeyInstructions': [
+ "Visit https://opencorporates.com/api_accounts/new"
+ "Register a new account with an email",
+ "Navigate to https://opencorporates.com/users/account and select 'Get Account'",
+ "Select the plan required",
+ "Navigate to https://opencorporates.com/users/account",
+ "The API key is listed under 'API Account'",
+ ],
+ 'favIcon': "https://opencorporates.com/assets/favicons/favicon.png",
+ 'logo': "https://opencorporates.com/contents/ui/theme/img/oc-logo.svg",
+ 'description': "The largest open database of companies in the world.\n"
+ "As the largest, open database of companies in the world, "
+ "our business is making high-quality, official company data openly available. "
+ "Data that can be trusted, accessed, analysed and interrogated when and how it’s needed.",
+ }
+ }
+
+ opts = {
+ 'confidence': 100,
+ 'api_key': ''
+ }
+
+ optdescs = {
+ 'confidence': "Confidence that the search result objects are correct (numeric value between 0 and 100).",
+ 'api_key': 'OpenCorporates.com API key. Without this you will be limited to 50 look-ups per day.'
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return ["COMPANY_NAME"]
+
+ def producedEvents(self):
+ return ["COMPANY_NAME", "PHYSICAL_ADDRESS", "RAW_RIR_DATA"]
+
+ def searchCompany(self, qry):
+ """Search for company name
+
+ Args:
+ qry (str): company name
+
+ Returns:
+ str
+ """
+
+ version = '0.4'
+
+ apiparam = ""
+ if self.opts['api_key']:
+ apiparam = "&api_token=" + self.opts['api_key']
+
+ params = urllib.parse.urlencode({
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'format': 'json',
+ 'order': 'score',
+ 'confidence': self.opts['confidence']
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.opencorporates.com/v{version}/companies/search?{params}{apiparam}",
+ timeout=60, # High timeouts as they can sometimes take a while
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "401":
+ self.error("Invalid OpenCorporates API key.")
+ return None
+
+ if res['code'] == "403":
+ self.error("You are being rate-limited by OpenCorporates.")
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if 'results' not in data:
+ return None
+
+ return data['results']
+
+ def retrieveCompanyDetails(self, jurisdiction_code, company_number):
+ url = f"https://api.opencorporates.com/companies/{jurisdiction_code}/{company_number}"
+
+ if self.opts['api_key']:
+ url += "?api_token=" + self.opts['api_key']
+
+ res = self.sf.fetchUrl(
+ url,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if res['code'] == "401":
+ self.error("Invalid OpenCorporates API key.")
+ return None
+
+ if res['code'] == "403":
+ self.error("You are being rate-limited by OpenCorporates.")
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+ return None
+
+ if 'results' not in data:
+ return None
+
+ return data['results']
+
+ # Extract company address, previous names, and officer names
+ def extractCompanyDetails(self, company, sevt):
+
+ # Extract registered address
+ location = company.get('registered_address_in_full')
+
+ if location:
+ if len(location) < 3 or len(location) > 100:
+ self.debug("Skipping likely invalid location.")
+ else:
+ if company.get('registered_address'):
+ country = company.get('registered_address').get('country')
+ if country:
+ if not location.endswith(country):
+ location += ", " + country
+
+ location = location.replace("\n", ',')
+ self.info("Found company address: " + location)
+ e = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, sevt)
+ self.notifyListeners(e)
+
+ # Extract previous company names
+ previous_names = company.get('previous_names')
+
+ if previous_names:
+ for previous_name in previous_names:
+ p = previous_name.get('company_name')
+ if p:
+ self.info("Found previous company name: " + p)
+ e = SpiderFootEvent("COMPANY_NAME", p, self.__name__, sevt)
+ self.notifyListeners(e)
+
+ # Extract officer names
+ officers = company.get('officers')
+
+ if officers:
+ for officer in officers:
+ n = officer.get('name')
+ if n:
+ self.info("Found company officer: " + n)
+ e = SpiderFootEvent("RAW_RIR_DATA", "Possible full name: " + n, self.__name__, sevt)
+ self.notifyListeners(e)
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if self.opts['api_key'] == '':
+ self.error(f"Warning: You enabled {self.__class__.__name__} but did not set an API key! Queries will be limited to 50 per day and 200 per month.")
+
+ res = self.searchCompany(f"{eventData}*")
+
+ if res is None:
+ self.debug("Found no results for " + eventData)
+ return
+
+ companies = res.get('companies')
+
+ if not companies:
+ self.debug("Found no results for " + eventData)
+ return
+
+ for c in companies:
+ company = c.get('company')
+
+ if not company:
+ continue
+
+ # Check for match
+ if eventData.lower() != company.get('name').lower():
+ continue
+
+ # Extract company details from search results
+ self.extractCompanyDetails(company, event)
+
+ # Retrieve further details
+ jurisdiction_code = company.get('jurisdiction_code')
+ company_number = company.get('company_number')
+
+ if not company_number or not jurisdiction_code:
+ continue
+
+ res = self.retrieveCompanyDetails(jurisdiction_code, company_number)
+
+ if not res:
+ continue
+
+ c = res.get('company')
+
+ if not c:
+ continue
+
+ self.extractCompanyDetails(c, event)
+
+# End of sfp_opencorporates class
diff --git a/spiderfoot/modules/sfp_opendns.py b/spiderfoot/modules/sfp_opendns.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f69b6696000306ee0653799f6e75c2faf7af5f7
--- /dev/null
+++ b/spiderfoot/modules/sfp_opendns.py
@@ -0,0 +1,143 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_opendns
+# Purpose: SpiderFoot plug-in for looking up whether hosts are blocked by
+# OpenDNS.
+#
+# Author: Steve Micallef
+#
+# Created: 30/05/2018
+# Copyright: (c) Steve Micallef 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_opendns(SpiderFootPlugin):
+
+ meta = {
+ 'name': "OpenDNS",
+ 'summary': "Check if a host would be blocked by OpenDNS.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://www.opendns.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://www.opendns.com/setupguide/?url=familyshield",
+ "https://support.opendns.com/hc/en-us/categories/204012807-OpenDNS-Knowledge-Base",
+ "https://support.opendns.com/hc/en-us/categories/204012907-OpenDNS-Device-Configuration"
+ ],
+ 'favIcon': "https://www.google.com/s2/favicons?domain=https://www.opendns.com/",
+ 'logo': "https://d15ni2z53ptwz9.cloudfront.net/opendns-www/img/logo-opendns.png",
+ 'description': "Cisco Umbrella provides protection against threats on the internet such as "
+ "malware, phishing, and ransomware.\n"
+ "OpenDNS is a suite of consumer products aimed at making your internet faster, safer, and more reliable. "
+ "FamilyShield is the single easiest way to protect your kids online, block adult websites, "
+ "and protect your family from phishing and malware.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ checks = {
+ "146.112.61.105": "OpenDNS - Botnet",
+ "146.112.61.106": "OpenDNS - Adult",
+ "146.112.61.107": "OpenDNS - Malware",
+ "146.112.61.108": "OpenDNS - Phishing",
+ "146.112.61.109": "OpenDNS - Blocked",
+ "146.112.61.110": "OpenDNS - Malware",
+ }
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE"
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryAddr(self, qaddr):
+ if not qaddr:
+ return None
+
+ res = dns.resolver.Resolver()
+ res.nameservers = ["208.67.222.123", "208.67.220.123"]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ res = self.queryAddr(eventData)
+
+ if not res:
+ return
+
+ self.debug(f"{eventData} found in OpenDNS Blocklist: {res}")
+
+ for result in res:
+ k = str(result)
+ if k not in self.checks:
+ continue
+
+ evt = SpiderFootEvent(blacklist_type, f"{self.checks[k]} [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+ if k in ['146.112.61.105', '146.112.61.107', '146.112.61.108', '146.112.61.110']:
+ evt = SpiderFootEvent(malicious_type, f"{self.checks[k]} [{eventData}]", self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_opendns class
diff --git a/spiderfoot/modules/sfp_opennic.py b/spiderfoot/modules/sfp_opennic.py
new file mode 100644
index 0000000000000000000000000000000000000000..786f6ec9edecfe4e8df16f6b5903d39a71fe5e68
--- /dev/null
+++ b/spiderfoot/modules/sfp_opennic.py
@@ -0,0 +1,175 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_opnenic
+# Purpose: SpiderFoot plug-in for resolving host names on the OpenNIC
+# alternative DNS system.
+#
+# Author:
+#
+# Created: 2021-10-16
+# Copyright: (c) bcoles 2021
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import dns.resolver
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_opennic(SpiderFootPlugin):
+
+ meta = {
+ 'name': "OpenNIC DNS",
+ 'summary': "Resolves host names in the OpenNIC alternative DNS system.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Footprint", "Passive"],
+ 'categories': ["DNS"],
+ 'dataSource': {
+ 'website': "https://www.opennic.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://wiki.opennic.org/",
+ "https://servers.opennic.org",
+ ],
+ 'description': "An organization of hobbyists who run an alternative DNS network, "
+ "also provides access to domains not administered by ICANN."
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "INTERNET_NAME_UNRESOLVED",
+ "AFFILIATE_INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME_UNRESOLVED",
+ ]
+
+ def producedEvents(self):
+ return [
+ "IP_ADDRESS",
+ "IPV6_ADDRESS",
+ "AFFILIATE_IPADDR",
+ "AFFILIATE_IPV6_ADDRESS",
+ ]
+
+ def queryOpenNIC(self, qaddr):
+ res = dns.resolver.Resolver()
+ # https://servers.opennicproject.org/
+ res.nameservers = [
+ "192.3.165.37",
+ "35.211.96.150",
+ "51.89.88.77",
+ "94.247.43.254",
+ "138.197.140.189"
+ ]
+
+ try:
+ return res.resolve(qaddr)
+ except Exception:
+ self.debug(f"Unable to resolve {qaddr}")
+
+ return None
+
+ def tlds(self):
+ """Valid OpenNIC top-level domains.
+
+ Returns:
+ list: OpenNIC TLDs (and peer TLDs).
+ """
+ return [
+ 'bbs',
+ 'chan',
+ 'cyb',
+ 'dyn',
+ 'epic',
+ 'free',
+ 'geek',
+ 'glue',
+ 'gopher',
+ 'indy',
+ 'libre',
+ 'neo',
+ 'null',
+ 'o',
+ 'oss',
+ 'oz',
+ 'parody',
+ 'pirate',
+
+ # Peers
+ 'bazar',
+ 'bit',
+ 'coin',
+ 'emc',
+ 'fur',
+ 'ku',
+ 'lib',
+ 'te',
+ 'ti',
+ 'uu',
+ ]
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ return
+
+ self.results[eventData] = True
+
+ if eventData.split('.')[-1] not in self.tlds():
+ return
+
+ affiliate = False
+
+ if "AFFILIATE" in eventName:
+ if not self.opts.get('checkaffiliates', False):
+ return
+ affiliate = True
+
+ addrs = self.sf.normalizeDNS(self.queryOpenNIC(eventData))
+
+ if not addrs:
+ return
+
+ self.debug(f"OpenNIC resolved {eventData} to addresses: {addrs}")
+
+ for addr in set(addrs):
+ if self.sf.validIP(addr):
+ if affiliate and not self.getTarget().matches(addr, includeParents=True):
+ evt = SpiderFootEvent("AFFILIATE_IPADDR", addr, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("IP_ADDRESS", addr, self.__name__, event)
+
+ self.notifyListeners(evt)
+ elif self.sf.validIP6(addr):
+ if affiliate and not self.getTarget().matches(addr, includeParents=True):
+ evt = SpiderFootEvent("AFFILIATE_IPV6_ADDRESS", addr, self.__name__, event)
+ else:
+ evt = SpiderFootEvent("IPV6_ADDRESS", addr, self.__name__, event)
+
+ self.notifyListeners(evt)
+ else:
+ continue
+
+# End of sfp_opennic class
diff --git a/spiderfoot/modules/sfp_openphish.py b/spiderfoot/modules/sfp_openphish.py
new file mode 100644
index 0000000000000000000000000000000000000000..f110920bfc927fde78ac6d581099e1ec6d76ce49
--- /dev/null
+++ b/spiderfoot/modules/sfp_openphish.py
@@ -0,0 +1,197 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_openphish
+# Purpose: Check if a host/domain is malicious according to OpenPhish.com.
+#
+# Author: steve@binarypool.com
+#
+# Created: 28/06/2018
+# Copyright: (c) Steve Micallef, 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_openphish(SpiderFootPlugin):
+
+ meta = {
+ 'name': "OpenPhish",
+ 'summary': "Check if a host/domain is malicious according to OpenPhish.com.",
+ 'flags': [],
+ 'useCases': ["Investigate", "Passive"],
+ 'categories': ["Reputation Systems"],
+ 'dataSource': {
+ 'website': "https://openphish.com/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://openphish.com/faq.html",
+ "https://openphish.com/feed.txt"
+ ],
+ 'favIcon': "",
+ 'logo': "https://openphish.com/static/openphish_logo2.png",
+ 'description': "Timely. Accurate. Relevant Threat Intelligence.\n"
+ "OpenPhish is a fully automated self-contained platform for phishing intelligence. "
+ "It identifies phishing sites and performs intelligence analysis ""in real time "
+ "without human intervention and without using any external resources, such as blacklists.",
+ }
+ }
+
+ opts = {
+ 'checkaffiliates': True,
+ 'checkcohosts': True,
+ 'cacheperiod': 18
+ }
+
+ optdescs = {
+ 'checkaffiliates': "Apply checks to affiliates?",
+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
+ 'cacheperiod': "Hours to cache list data before re-fetching."
+ }
+
+ results = None
+ errorState = False
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+ self.errorState = False
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ def watchedEvents(self):
+ return [
+ "INTERNET_NAME",
+ "AFFILIATE_INTERNET_NAME",
+ "CO_HOSTED_SITE",
+ ]
+
+ def producedEvents(self):
+ return [
+ "BLACKLISTED_INTERNET_NAME",
+ "BLACKLISTED_AFFILIATE_INTERNET_NAME",
+ "BLACKLISTED_COHOST",
+ "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_COHOST",
+ ]
+
+ def queryBlacklist(self, target):
+ blacklist = self.retrieveBlacklist()
+
+ if not blacklist:
+ return False
+
+ if target.lower() in blacklist:
+ self.debug(f"Host name {target} found in OpenPhish blacklist.")
+ return True
+
+ return False
+
+ def retrieveBlacklist(self):
+ blacklist = self.sf.cacheGet('openphish', 24)
+
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ res = self.sf.fetchUrl(
+ "https://www.openphish.com/feed.txt",
+ timeout=10,
+ useragent=self.opts['_useragent'],
+ )
+
+ if res['code'] != "200":
+ self.error(f"Unexpected HTTP response code {res['code']} from OpenPhish.")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.error("Received no content from OpenPhish")
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("openphish", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+
+ Args:
+ blacklist (str): plaintext blacklist from OpenPhish
+
+ Returns:
+ list: list of blacklisted host names
+ """
+ hosts = list()
+
+ if not blacklist:
+ return hosts
+
+ for line in blacklist.split('\n'):
+ if not line:
+ continue
+ if not line.startswith('http'):
+ continue
+
+ # Note: URL parsing and validation with sf.validHost() is too slow to use here
+ url = line.strip().lower()
+ if len(url.split("/")) < 3:
+ continue
+ host = url.split("/")[2]
+ if not host:
+ continue
+ if "." not in host:
+ continue
+ hosts.append(host)
+
+ return hosts
+
+ def handleEvent(self, event):
+ eventName = event.eventType
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ if self.errorState:
+ return
+
+ self.results[eventData] = True
+
+ if eventName == "INTERNET_NAME":
+ malicious_type = "MALICIOUS_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_INTERNET_NAME"
+ elif eventName == "AFFILIATE_INTERNET_NAME":
+ if not self.opts.get('checkaffiliates', False):
+ return
+ malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
+ elif eventName == "CO_HOSTED_SITE":
+ if not self.opts.get('checkcohosts', False):
+ return
+ malicious_type = "MALICIOUS_COHOST"
+ blacklist_type = "BLACKLISTED_COHOST"
+ else:
+ self.debug(f"Unexpected event type {eventName}, skipping")
+ return
+
+ self.debug(f"Checking maliciousness of {eventData} ({eventName}) with OpenPhish")
+
+ if not self.queryBlacklist(eventData):
+ return
+
+ url = "https://www.openphish.com/feed.txt"
+ text = f"OpenPhish [{eventData}]\n{url} "
+
+ evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+ evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_openphish class
diff --git a/spiderfoot/modules/sfp_openstreetmap.py b/spiderfoot/modules/sfp_openstreetmap.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a0d788051b76cc06993d156d681a5315a4f143d
--- /dev/null
+++ b/spiderfoot/modules/sfp_openstreetmap.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_openstreetmap
+# Purpose: SpiderFoot plug-in to retrieve latitude/longitude coordinates
+# for physical addresses from OpenStreetMap API.
+#
+# Author:
+#
+# Created: 2018-10-27
+# Copyright: (c) bcoles 2018
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import json
+import re
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+
+class sfp_openstreetmap(SpiderFootPlugin):
+
+ meta = {
+ 'name': "OpenStreetMap",
+ 'summary': "Retrieves latitude/longitude coordinates for physical addresses from OpenStreetMap API.",
+ 'flags': [],
+ 'useCases': ["Footprint", "Investigate", "Passive"],
+ 'categories': ["Real World"],
+ 'dataSource': {
+ 'website': "https://www.openstreetmap.org/",
+ 'model': "FREE_NOAUTH_UNLIMITED",
+ 'references': [
+ "https://wiki.openstreetmap.org/wiki/API",
+ "https://wiki.openstreetmap.org/wiki/API_v0.6"
+ ],
+ 'favIcon': "https://www.openstreetmap.org/assets/osm_logo-b7061f13a03615f787a7e0e56a0db5252eb2a217ab063183e78526a8cc10989b.svg",
+ 'logo': "https://www.openstreetmap.org/assets/osm_logo-b7061f13a03615f787a7e0e56a0db5252eb2a217ab063183e78526a8cc10989b.svg",
+ 'description': "OpenStreetMap powers map data on thousands of web sites, mobile apps, and hardware devices.",
+ }
+ }
+
+ opts = {
+ }
+
+ optdescs = {
+ }
+
+ results = None
+
+ def setup(self, sfc, userOpts=dict()):
+ self.sf = sfc
+ self.results = self.tempStorage()
+
+ for opt in list(userOpts.keys()):
+ self.opts[opt] = userOpts[opt]
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['PHYSICAL_ADDRESS']
+
+ # What events this module produces
+ def producedEvents(self):
+ return ['PHYSICAL_COORDINATES']
+
+ # Search for address
+ # https://operations.osmfoundation.org/policies/nominatim/
+ def query(self, qry):
+ params = {
+ 'q': qry.encode('raw_unicode_escape').decode("ascii", errors='replace'),
+ 'format': 'json',
+ 'polygon': '0',
+ 'addressdetails': '0'
+ }
+
+ res = self.sf.fetchUrl("https://nominatim.openstreetmap.org/search?" + urllib.parse.urlencode(params),
+ timeout=self.opts['_fetchtimeout'], useragent='SpiderFoot')
+
+ if res['content'] is None:
+ self.info("No location info found for " + qry)
+ return None
+
+ try:
+ return json.loads(res['content'])
+ except Exception as e:
+ self.debug(f"Error processing JSON response: {e}")
+
+ return None
+
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+
+ self.debug(f"Received event, {eventName}, from {srcModuleName}")
+
+ if eventData in self.results:
+ self.debug(f"Skipping {eventData}, already checked.")
+ return
+
+ self.results[eventData] = True
+
+ address = eventData
+
+ # Skip post office boxes
+ if address.lower().startswith('po box'):
+ self.debug("Skipping PO BOX address")
+ return
+
+ rx1 = re.compile(r'^(c/o|care of|attn:|attention:)\s+[0-9a-z\s\.]', flags=re.IGNORECASE)
+ # Remove address prefixes for delivery instructions
+ address = re.sub(rx1, r'', address)
+
+ rx2 = re.compile(r'^(Level|Floor|Suite|Room)\s+[0-9a-z]+,', flags=re.IGNORECASE)
+ # Remove address prefixes known to return no results (floor, level, suite, etc).
+ address = re.sub(rx2, r'', address)
+
+ # Search for address
+ data = self.query(eventData)
+
+ # Usage Policy mandates no more than 1 request per second
+ time.sleep(1)
+
+ if data is None:
+ self.debug("Found no results for " + eventData)
+ return
+
+ self.info("Found " + str(len(data)) + " matches for " + eventData)
+
+ for location in data:
+ try:
+ lat = location.get('lat')
+ lon = location.get('lon')
+ except Exception as e:
+ self.debug("Failed to get lat/lon: " + str(e))
+ continue
+
+ if not lat or not lon:
+ continue
+
+ coords = str(lat) + "," + str(lon)
+ self.debug("Found coordinates: " + coords)
+
+ evt = SpiderFootEvent("PHYSICAL_COORDINATES", coords, self.__name__, event)
+ self.notifyListeners(evt)
+
+# End of sfp_openstreetmap class
diff --git a/spiderfoot/modules/sfp_pageinfo.py b/spiderfoot/modules/sfp_pageinfo.py
new file mode 100644
index 0000000000000000000000000000000000000000..53930614217b050877512810dd3e44c1558f052b
--- /dev/null
+++ b/spiderfoot/modules/sfp_pageinfo.py
@@ -0,0 +1,138 @@
+# -*- coding: utf-8 -*-
+# -------------------------------------------------------------------------------
+# Name: sfp_pageinfo
+# Purpose: SpiderFoot plug-in for scanning retrieved content by other
+# modules (such as sfp_spider) and building up information about
+# the page, such as whether it uses Javascript, has forms, and more.
+#
+# Author: Steve Micallef
+#
+# Created: 02/05/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: MIT
+# -------------------------------------------------------------------------------
+
+import re
+
+from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+
+# Indentify pages that use Javascript libs, handle passwords, have forms,
+# permit file uploads and more to come.
+regexps = dict({
+ 'URL_JAVASCRIPT': list(['text/javascript', '