Compare commits
36 Commits
140ef54674
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b20bfd2e36 | ||
|
|
c3534868ad | ||
| 36c0bcdc03 | |||
|
|
ceb2d2fffc | ||
|
|
60cd649961 | ||
|
|
64309c53b7 | ||
|
|
50fc5176a6 | ||
|
|
3951b9e521 | ||
|
|
897bb80183 | ||
|
|
571912218e | ||
|
|
5d1d249910 | ||
|
|
52ea7acf04 | ||
|
|
513eff12ef | ||
|
|
4c361c144d | ||
|
|
b2629de055 | ||
|
|
b2c5d2331c | ||
|
|
602739246f | ||
|
|
4a82c279ef | ||
|
|
71a05f5b32 | ||
|
|
1b0c630667 | ||
|
|
bcd79ae2f5 | ||
| 3ee23c9d05 | |||
|
|
8d402ab4b1 | ||
|
|
7472e6f416 | ||
|
|
eabb532557 | ||
|
|
0a6d12de9a | ||
|
|
332805709d | ||
|
|
1558731c1c | ||
|
|
95cebbf935 | ||
|
|
4c48917993 | ||
|
|
9d9afa6a08 | ||
|
|
12f834bb65 | ||
|
|
cbfd40ee98 | ||
|
|
d4081e1a32 | ||
|
|
15227b392d | ||
|
|
fdc26dcf15 |
@@ -1,5 +1,5 @@
|
||||
# ===============================================
|
||||
# DNSRecon Environment Variables
|
||||
# DNScope Environment Variables
|
||||
# ===============================================
|
||||
# Copy this file to .env and fill in your values.
|
||||
|
||||
@@ -32,3 +32,5 @@ LARGE_ENTITY_THRESHOLD=100
|
||||
MAX_RETRIES_PER_TARGET=8
|
||||
# How long cached provider responses are stored (in hours).
|
||||
CACHE_TIMEOUT_HOURS=12
|
||||
|
||||
GRAPH_POLLING_NODE_THRESHOLD=100
|
||||
|
||||
202
README.md
202
README.md
@@ -1,14 +1,18 @@
|
||||
# DNSRecon - Passive Infrastructure Reconnaissance Tool
|
||||
# DNScope - Passive Infrastructure Reconnaissance Tool
|
||||
|
||||
DNSRecon is an interactive, passive reconnaissance tool designed to map adversary infrastructure. It operates on a "free-by-default" model, ensuring core functionality without subscriptions, while allowing power users to enhance its capabilities with paid API keys.
|
||||
DNScope is an interactive, passive reconnaissance tool designed to map adversary infrastructure. It operates on a "free-by-default" model, ensuring core functionality without subscriptions, while allowing power users to enhance its capabilities with paid API keys. It is aimed at cybersecurity researchers, pentesters, and administrators who want to understand the public footprint of a target domain.
|
||||
|
||||
**Current Status: Phase 2 Implementation**
|
||||
**Repo Link:** [https://github.com/overcuriousity/DNScope](https://github.com/overcuriousity/DNScope)
|
||||
|
||||
* ✅ Core infrastructure and graph engine
|
||||
* ✅ Multi-provider support (crt.sh, DNS, Shodan)
|
||||
* ✅ Session-based multi-user support
|
||||
* ✅ Real-time web interface with interactive visualization
|
||||
* ✅ Forensic logging system and JSON export
|
||||
-----
|
||||
|
||||
## Concept and Philosophy
|
||||
|
||||
The core philosophy of DNScope is to provide a comprehensive and accurate map of a target's infrastructure using only **passive data sources** by default. This means that, out of the box, DNScope will not send any traffic to the target's servers. Instead, it queries public and historical data sources to build a picture of the target's online presence. This approach is ideal for researchers and pentesters who want to gather intelligence without alerting the target, and for administrators who want to see what information about their own infrastructure is publicly available.
|
||||
|
||||
For power users who require more in-depth information, DNScope can be configured to use API keys for services like Shodan, which provides a wealth of information about internet-connected devices. However, this is an optional feature, and the core functionality of the tool will always remain free and passive.
|
||||
|
||||
-----
|
||||
|
||||
-----
|
||||
|
||||
@@ -18,27 +22,81 @@ DNSRecon is an interactive, passive reconnaissance tool designed to map adversar
|
||||
* **In-Memory Graph Analysis**: Uses NetworkX for efficient relationship mapping.
|
||||
* **Real-Time Visualization**: The graph updates dynamically as the scan progresses.
|
||||
* **Forensic Logging**: A complete audit trail of all reconnaissance activities is maintained.
|
||||
* **Confidence Scoring**: Relationships are weighted based on the reliability of the data source.
|
||||
* **Session Management**: Supports concurrent user sessions with isolated scanner instances.
|
||||
* **Extensible Provider Architecture**: Easily add new data sources to expand the tool's capabilities.
|
||||
* **Web-Based UI**: An intuitive and interactive web interface for managing scans and visualizing results.
|
||||
* **Export Options**: Export scan results to JSON, a list of targets to a text file, or an executive summary.
|
||||
* **API Key Management**: Securely manage API keys for various providers through the web interface.
|
||||
* **Provider Management**: Enable or disable providers for the current session.
|
||||
|
||||
-----
|
||||
|
||||
## Installation
|
||||
## Technical Architecture
|
||||
|
||||
DNScope is a web-based application built with a modern technology stack:
|
||||
|
||||
* **Backend**: The backend is a **Flask** application that provides a REST API for the frontend and manages the scanning process.
|
||||
* **Scanning Engine**: The core scanning engine is a multi-threaded Python application that uses a provider-based architecture to query different data sources.
|
||||
* **Session Management**: **Redis** is used for session management, allowing for concurrent user sessions with isolated scanner instances.
|
||||
* **Data Storage**: The application uses an in-memory graph to store and analyze the relationships between different pieces of information. The graph is built using the **NetworkX** library.
|
||||
* **Frontend**: The frontend is a single-page application that uses JavaScript to interact with the backend API and visualize the graph.
|
||||
|
||||
-----
|
||||
|
||||
## Data Sources
|
||||
|
||||
DNScope queries the following data sources:
|
||||
|
||||
* **DNS**: Standard DNS lookups (A, AAAA, CNAME, MX, NS, SOA, TXT).
|
||||
* **crt.sh**: A certificate transparency log that provides information about SSL/TLS certificates.
|
||||
* **Shodan**: A search engine for internet-connected devices (requires an API key).
|
||||
|
||||
-----
|
||||
|
||||
## Installation and Setup
|
||||
|
||||
### Prerequisites
|
||||
|
||||
* Python 3.8 or higher
|
||||
* A modern web browser with JavaScript enabled
|
||||
* (Recommended) A Linux host for running the application and the optional DNS cache.
|
||||
* A Linux host for running the application
|
||||
* Redis Server
|
||||
|
||||
### 1\. Clone the Project
|
||||
### 1\. Install Redis
|
||||
|
||||
It is recommended to install Redis from the official repositories.
|
||||
|
||||
**On Debian/Ubuntu:**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-repo/dnsrecon.git
|
||||
cd dnsrecon
|
||||
sudo apt-get update
|
||||
sudo apt-get install redis-server
|
||||
```
|
||||
|
||||
### 2\. Install Python Dependencies
|
||||
**On CentOS/RHEL:**
|
||||
|
||||
```bash
|
||||
sudo yum install redis
|
||||
sudo systemctl start redis
|
||||
sudo systemctl enable redis
|
||||
```
|
||||
|
||||
You can verify that Redis is running with the following command:
|
||||
|
||||
```bash
|
||||
redis-cli ping
|
||||
```
|
||||
|
||||
You should see `PONG` as the response.
|
||||
|
||||
### 2\. Clone the Project
|
||||
|
||||
```bash
|
||||
git clone https://github.com/overcuriousity/DNScope
|
||||
cd DNScope
|
||||
```
|
||||
|
||||
### 3\. Install Python Dependencies
|
||||
|
||||
It is highly recommended to use a virtual environment:
|
||||
|
||||
@@ -50,22 +108,21 @@ pip install -r requirements.txt
|
||||
|
||||
The `requirements.txt` file contains the following dependencies:
|
||||
|
||||
* Flask\>=2.3.3
|
||||
* networkx\>=3.1
|
||||
* requests\>=2.31.0
|
||||
* python-dateutil\>=2.8.2
|
||||
* Werkzeug\>=2.3.7
|
||||
* urllib3\>=2.0.0
|
||||
* dnspython\>=2.4.2
|
||||
* Flask
|
||||
* networkx
|
||||
* requests
|
||||
* python-dateutil
|
||||
* Werkzeug
|
||||
* urllib3
|
||||
* dnspython
|
||||
* gunicorn
|
||||
* redis
|
||||
* python-dotenv
|
||||
* psycopg2-binary
|
||||
|
||||
-----
|
||||
### 4\. Configure the Application
|
||||
|
||||
## Configuration
|
||||
|
||||
DNSRecon is configured using a `.env` file. You can copy the provided example file and edit it to suit your needs:
|
||||
DNScope is configured using a `.env` file. You can copy the provided example file and edit it to suit your needs:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
@@ -91,32 +148,48 @@ The following environment variables are available for configuration:
|
||||
|
||||
-----
|
||||
|
||||
## Running the Application
|
||||
|
||||
For development, you can run the application using the following command:
|
||||
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
For production, it is recommended to use a more robust server, such as Gunicorn:
|
||||
|
||||
```bash
|
||||
gunicorn --workers 4 --bind 0.0.0.0:5000 app:app
|
||||
```
|
||||
|
||||
-----
|
||||
|
||||
## Systemd Service
|
||||
|
||||
To run DNSRecon as a service that starts automatically on boot, you can use `systemd`.
|
||||
To run DNScope as a service that starts automatically on boot, you can use `systemd`.
|
||||
|
||||
### 1\. Create a `.service` file
|
||||
|
||||
Create a new service file in `/etc/systemd/system/`:
|
||||
|
||||
```bash
|
||||
sudo nano /etc/systemd/system/dnsrecon.service
|
||||
sudo nano /etc/systemd/system/DNScope.service
|
||||
```
|
||||
|
||||
### 2\. Add the Service Configuration
|
||||
|
||||
Paste the following configuration into the file. **Remember to replace `/path/to/your/dnsrecon` and `your_user` with your actual project path and username.**
|
||||
Paste the following configuration into the file. **Remember to replace `/path/to/your/DNScope` and `your_user` with your actual project path and username.**
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=DNSRecon Application
|
||||
Description=DNScope Application
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=your_user
|
||||
Group=your_user
|
||||
WorkingDirectory=/path/to/your/dnsrecon
|
||||
ExecStart=/path/to/your/dnsrecon/venv/bin/gunicorn --workers 4 --bind 0.0.0.0:5000 app:app
|
||||
WorkingDirectory=/path/to/your/DNScope
|
||||
ExecStart=/path/to/your/DNScope/venv/bin/gunicorn --workers 4 --bind 0.0.0.0:5000 app:app
|
||||
Restart=always
|
||||
Environment="SECRET_KEY=your-super-secret-and-random-key"
|
||||
Environment="FLASK_ENV=production"
|
||||
@@ -133,18 +206,77 @@ Reload the `systemd` daemon, enable the service to start on boot, and then start
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable dnsrecon.service
|
||||
sudo systemctl start dnsrecon.service
|
||||
sudo systemctl enable DNScope.service
|
||||
sudo systemctl start DNScope.service
|
||||
```
|
||||
|
||||
You can check the status of the service at any time with:
|
||||
|
||||
```bash
|
||||
sudo systemctl status dnsrecon.service
|
||||
sudo systemctl status DNScope.service
|
||||
```
|
||||
|
||||
-----
|
||||
|
||||
## Updating the Application
|
||||
|
||||
To update the application, you should first pull the latest changes from the git repository. Then, you will need to wipe the Redis database and the local cache to ensure that you are using the latest data.
|
||||
|
||||
### 1\. Update the Code
|
||||
|
||||
```bash
|
||||
git pull
|
||||
```
|
||||
|
||||
### 2\. Wipe the Redis Database
|
||||
|
||||
```bash
|
||||
redis-cli FLUSHALL
|
||||
```
|
||||
|
||||
### 3\. Wipe the Local Cache
|
||||
|
||||
```bash
|
||||
rm -rf cache/*
|
||||
```
|
||||
|
||||
### 4\. Restart the Service
|
||||
|
||||
```bash
|
||||
sudo systemctl restart DNScope.service
|
||||
```
|
||||
|
||||
-----
|
||||
|
||||
## Extensibility
|
||||
|
||||
DNScope is designed to be extensible, and adding new providers is a straightforward process. To add a new provider, you will need to create a new Python file in the `providers` directory that inherits from the `BaseProvider` class. The new provider will need to implement the following methods:
|
||||
|
||||
* `get_name()`: Return the name of the provider.
|
||||
* `get_display_name()`: Return a display-friendly name for the provider.
|
||||
* `requires_api_key()`: Return `True` if the provider requires an API key.
|
||||
* `get_eligibility()`: Return a dictionary indicating whether the provider can query domains and/or IPs.
|
||||
* `is_available()`: Return `True` if the provider is available (e.g., if an API key is configured).
|
||||
* `query_domain(domain)`: Query the provider for information about a domain.
|
||||
* `query_ip(ip)`: Query the provider for information about an IP address.
|
||||
|
||||
-----
|
||||
|
||||
## Unique Capabilities and Limitations
|
||||
|
||||
### Unique Capabilities
|
||||
|
||||
* **Graph-Based Analysis**: The use of a graph-based data model allows for a more intuitive and powerful analysis of the relationships between different pieces of information.
|
||||
* **Real-Time Visualization**: The real-time visualization of the graph provides immediate feedback and allows for a more interactive and engaging analysis experience.
|
||||
* **Session Management**: The session management feature allows multiple users to use the application concurrently without interfering with each other's work.
|
||||
|
||||
### Limitations
|
||||
|
||||
* **Passive-Only by Default**: While the passive-only approach is a key feature of the tool, it also means that the information it can gather is limited to what is publicly available.
|
||||
* **No Active Scanning**: The tool does not perform any active scanning, such as port scanning or vulnerability scanning.
|
||||
|
||||
-----
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the **BSD-3-Clause** license.
|
||||
|
||||
243
app.py
243
app.py
@@ -1,8 +1,9 @@
|
||||
# dnsrecon-reduced/app.py
|
||||
# DNScope-reduced/app.py
|
||||
|
||||
"""
|
||||
Flask application entry point for DNSRecon web interface.
|
||||
Flask application entry point for DNScope web interface.
|
||||
Provides REST API endpoints and serves the web interface with user session support.
|
||||
UPDATED: Added /api/config endpoint for graph polling optimization settings.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -16,6 +17,7 @@ from core.session_manager import session_manager
|
||||
from config import config
|
||||
from core.graph_manager import NodeType
|
||||
from utils.helpers import is_valid_target
|
||||
from utils.export_manager import export_manager
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
@@ -27,7 +29,7 @@ def get_user_scanner():
|
||||
"""
|
||||
Retrieves the scanner for the current session, or creates a new one if none exists.
|
||||
"""
|
||||
current_flask_session_id = session.get('dnsrecon_session_id')
|
||||
current_flask_session_id = session.get('DNScope_session_id')
|
||||
|
||||
if current_flask_session_id:
|
||||
existing_scanner = session_manager.get_session(current_flask_session_id)
|
||||
@@ -40,39 +42,33 @@ def get_user_scanner():
|
||||
if not new_scanner:
|
||||
raise Exception("Failed to create new scanner session")
|
||||
|
||||
session['dnsrecon_session_id'] = new_session_id
|
||||
session['DNScope_session_id'] = new_session_id
|
||||
session.permanent = True
|
||||
|
||||
return new_session_id, new_scanner
|
||||
|
||||
class CustomJSONEncoder(json.JSONEncoder):
|
||||
"""Custom JSON encoder to handle non-serializable objects."""
|
||||
|
||||
def default(self, obj):
|
||||
if isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, set):
|
||||
return list(obj)
|
||||
elif isinstance(obj, Decimal):
|
||||
return float(obj)
|
||||
elif hasattr(obj, '__dict__'):
|
||||
# For custom objects, try to serialize their dict representation
|
||||
try:
|
||||
return obj.__dict__
|
||||
except:
|
||||
return str(obj)
|
||||
elif hasattr(obj, 'value') and hasattr(obj, 'name'):
|
||||
# For enum objects
|
||||
return obj.value
|
||||
else:
|
||||
# For any other non-serializable object, convert to string
|
||||
return str(obj)
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""Serve the main web interface."""
|
||||
return render_template('index.html')
|
||||
|
||||
|
||||
@app.route('/api/config', methods=['GET'])
|
||||
def get_config():
|
||||
"""Get configuration settings for frontend."""
|
||||
try:
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'config': {
|
||||
'graph_polling_node_threshold': config.graph_polling_node_threshold
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'error': f'Internal server error: {str(e)}'}), 500
|
||||
|
||||
|
||||
@app.route('/api/scan/start', methods=['POST'])
|
||||
def start_scan():
|
||||
"""
|
||||
@@ -105,7 +101,7 @@ def start_scan():
|
||||
if success:
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': 'Scan started successfully',
|
||||
'message': 'Reconnaissance scan started successfully',
|
||||
'scan_id': scanner.logger.session_id,
|
||||
'user_session_id': user_session_id
|
||||
})
|
||||
@@ -207,7 +203,9 @@ def get_graph_data():
|
||||
|
||||
@app.route('/api/graph/large-entity/extract', methods=['POST'])
|
||||
def extract_from_large_entity():
|
||||
"""Extract a node from a large entity."""
|
||||
"""
|
||||
FIXED: Extract a node from a large entity with proper error handling.
|
||||
"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
large_entity_id = data.get('large_entity_id')
|
||||
@@ -220,17 +218,66 @@ def extract_from_large_entity():
|
||||
if not scanner:
|
||||
return jsonify({'success': False, 'error': 'No active session found'}), 404
|
||||
|
||||
# FIXED: Check if node exists and provide better error messages
|
||||
if not scanner.graph.graph.has_node(node_id):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Node {node_id} not found in graph'
|
||||
}), 404
|
||||
|
||||
# FIXED: Check if node is actually part of the large entity
|
||||
node_data = scanner.graph.graph.nodes[node_id]
|
||||
metadata = node_data.get('metadata', {})
|
||||
current_large_entity = metadata.get('large_entity_id')
|
||||
|
||||
if not current_large_entity:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Node {node_id} is not part of any large entity'
|
||||
}), 400
|
||||
|
||||
if current_large_entity != large_entity_id:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Node {node_id} belongs to large entity {current_large_entity}, not {large_entity_id}'
|
||||
}), 400
|
||||
|
||||
# FIXED: Check if large entity exists
|
||||
if not scanner.graph.graph.has_node(large_entity_id):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Large entity {large_entity_id} not found'
|
||||
}), 404
|
||||
|
||||
# Perform the extraction
|
||||
success = scanner.extract_node_from_large_entity(large_entity_id, node_id)
|
||||
|
||||
if success:
|
||||
# Force immediate session state update
|
||||
session_manager.update_session_scanner(user_session_id, scanner)
|
||||
return jsonify({'success': True, 'message': f'Node {node_id} extracted successfully.'})
|
||||
else:
|
||||
return jsonify({'success': False, 'error': f'Failed to extract node {node_id}.'}), 500
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': f'Node {node_id} extracted successfully from {large_entity_id}.',
|
||||
'extracted_node': node_id,
|
||||
'large_entity': large_entity_id
|
||||
})
|
||||
else:
|
||||
# This should not happen with the improved checks above, but handle it gracefully
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Failed to extract node {node_id} from {large_entity_id}. Node may have already been extracted.'
|
||||
}), 409
|
||||
|
||||
except json.JSONDecodeError:
|
||||
return jsonify({'success': False, 'error': 'Invalid JSON in request body'}), 400
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'error': f'Internal server error: {str(e)}'}), 500
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Internal server error: {str(e)}',
|
||||
'error_type': type(e).__name__
|
||||
}), 500
|
||||
|
||||
@app.route('/api/graph/node/<node_id>', methods=['DELETE'])
|
||||
def delete_graph_node(node_id):
|
||||
@@ -285,7 +332,6 @@ def revert_graph_action():
|
||||
scanner.graph.add_edge(
|
||||
source_id=edge['from'], target_id=edge['to'],
|
||||
relationship_type=edge['metadata']['relationship_type'],
|
||||
confidence_score=edge['metadata']['confidence_score'],
|
||||
source_provider=edge['metadata']['source_provider'],
|
||||
raw_data=edge.get('raw_data', {})
|
||||
)
|
||||
@@ -309,40 +355,29 @@ def export_results():
|
||||
if not scanner:
|
||||
return jsonify({'success': False, 'error': 'No active scanner session found'}), 404
|
||||
|
||||
# Get export data with error handling
|
||||
# Get export data using the new export manager
|
||||
try:
|
||||
results = scanner.export_results()
|
||||
results = export_manager.export_scan_results(scanner)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': f'Failed to gather export data: {str(e)}'}), 500
|
||||
|
||||
# Add export metadata
|
||||
results['export_metadata'] = {
|
||||
'user_session_id': user_session_id,
|
||||
'export_timestamp': datetime.now(timezone.utc).isoformat(),
|
||||
'export_version': '1.0.0',
|
||||
'forensic_integrity': 'maintained'
|
||||
}
|
||||
# Add user session metadata
|
||||
results['export_metadata']['user_session_id'] = user_session_id
|
||||
results['export_metadata']['forensic_integrity'] = 'maintained'
|
||||
|
||||
# Generate filename with forensic naming convention
|
||||
timestamp = datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')
|
||||
target = scanner.current_target or 'unknown'
|
||||
# Sanitize target for filename
|
||||
safe_target = "".join(c for c in target if c.isalnum() or c in ('-', '_', '.')).rstrip()
|
||||
filename = f"dnsrecon_{safe_target}_{timestamp}.json"
|
||||
# Generate filename
|
||||
filename = export_manager.generate_filename(
|
||||
target=scanner.current_target or 'unknown',
|
||||
export_type='json'
|
||||
)
|
||||
|
||||
# Serialize with custom encoder and error handling
|
||||
# Serialize with export manager
|
||||
try:
|
||||
json_data = json.dumps(results, indent=2, cls=CustomJSONEncoder, ensure_ascii=False)
|
||||
json_data = export_manager.serialize_to_json(results)
|
||||
except Exception as e:
|
||||
# If custom encoder fails, try a more aggressive approach
|
||||
try:
|
||||
# Convert problematic objects to strings recursively
|
||||
cleaned_results = _clean_for_json(results)
|
||||
json_data = json.dumps(cleaned_results, indent=2, ensure_ascii=False)
|
||||
except Exception as e2:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'JSON serialization failed: {str(e2)}'
|
||||
'error': f'JSON serialization failed: {str(e)}'
|
||||
}), 500
|
||||
|
||||
# Create file object
|
||||
@@ -363,48 +398,64 @@ def export_results():
|
||||
'error_type': type(e).__name__
|
||||
}), 500
|
||||
|
||||
def _clean_for_json(obj, max_depth=10, current_depth=0):
|
||||
"""
|
||||
Recursively clean an object to make it JSON serializable.
|
||||
Handles circular references and problematic object types.
|
||||
"""
|
||||
if current_depth > max_depth:
|
||||
return f"<max_depth_exceeded_{type(obj).__name__}>"
|
||||
@app.route('/api/export/targets', methods=['GET'])
|
||||
def export_targets():
|
||||
"""Export all discovered targets as a TXT file."""
|
||||
try:
|
||||
user_session_id, scanner = get_user_scanner()
|
||||
if not scanner:
|
||||
return jsonify({'success': False, 'error': 'No active scanner session found'}), 404
|
||||
|
||||
if obj is None or isinstance(obj, (bool, int, float, str)):
|
||||
return obj
|
||||
elif isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, (set, frozenset)):
|
||||
return list(obj)
|
||||
elif isinstance(obj, dict):
|
||||
cleaned = {}
|
||||
for key, value in obj.items():
|
||||
# Use export manager for targets export
|
||||
targets_txt = export_manager.export_targets_list(scanner)
|
||||
|
||||
# Generate filename using export manager
|
||||
filename = export_manager.generate_filename(
|
||||
target=scanner.current_target or 'unknown',
|
||||
export_type='targets'
|
||||
)
|
||||
|
||||
file_obj = io.BytesIO(targets_txt.encode('utf-8'))
|
||||
|
||||
return send_file(
|
||||
file_obj,
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype='text/plain'
|
||||
)
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'error': f'Export failed: {str(e)}'}), 500
|
||||
|
||||
|
||||
@app.route('/api/export/summary', methods=['GET'])
|
||||
def export_summary():
|
||||
"""Export an executive summary as a TXT file."""
|
||||
try:
|
||||
# Ensure key is string
|
||||
clean_key = str(key) if not isinstance(key, str) else key
|
||||
cleaned[clean_key] = _clean_for_json(value, max_depth, current_depth + 1)
|
||||
except Exception:
|
||||
cleaned[str(key)] = f"<serialization_error_{type(value).__name__}>"
|
||||
return cleaned
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
cleaned = []
|
||||
for item in obj:
|
||||
try:
|
||||
cleaned.append(_clean_for_json(item, max_depth, current_depth + 1))
|
||||
except Exception:
|
||||
cleaned.append(f"<serialization_error_{type(item).__name__}>")
|
||||
return cleaned
|
||||
elif hasattr(obj, '__dict__'):
|
||||
try:
|
||||
return _clean_for_json(obj.__dict__, max_depth, current_depth + 1)
|
||||
except Exception:
|
||||
return str(obj)
|
||||
elif hasattr(obj, 'value'):
|
||||
# For enum-like objects
|
||||
return obj.value
|
||||
else:
|
||||
return str(obj)
|
||||
user_session_id, scanner = get_user_scanner()
|
||||
if not scanner:
|
||||
return jsonify({'success': False, 'error': 'No active scanner session found'}), 404
|
||||
|
||||
# Use export manager for summary generation
|
||||
summary_txt = export_manager.generate_executive_summary(scanner)
|
||||
|
||||
# Generate filename using export manager
|
||||
filename = export_manager.generate_filename(
|
||||
target=scanner.current_target or 'unknown',
|
||||
export_type='summary'
|
||||
)
|
||||
|
||||
file_obj = io.BytesIO(summary_txt.encode('utf-8'))
|
||||
|
||||
return send_file(
|
||||
file_obj,
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype='text/plain'
|
||||
)
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
return jsonify({'success': False, 'error': f'Export failed: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/config/api-keys', methods=['POST'])
|
||||
def set_api_keys():
|
||||
|
||||
18
config.py
18
config.py
@@ -1,7 +1,7 @@
|
||||
# dnsrecon-reduced/config.py
|
||||
# DNScope-reduced/config.py
|
||||
|
||||
"""
|
||||
Configuration management for DNSRecon tool.
|
||||
Configuration management for DNScope tool.
|
||||
Handles API key storage, rate limiting, and default settings.
|
||||
"""
|
||||
|
||||
@@ -13,7 +13,7 @@ from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
class Config:
|
||||
"""Configuration manager for DNSRecon application."""
|
||||
"""Configuration manager for DNScope application."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize configuration with default values."""
|
||||
@@ -26,6 +26,9 @@ class Config:
|
||||
self.large_entity_threshold = 100
|
||||
self.max_retries_per_target = 8
|
||||
|
||||
# --- Graph Polling Performance Settings ---
|
||||
self.graph_polling_node_threshold = 100 # Stop graph auto-polling above this many nodes
|
||||
|
||||
# --- Provider Caching Settings ---
|
||||
self.cache_timeout_hours = 6 # Provider-specific cache timeout
|
||||
|
||||
@@ -33,14 +36,16 @@ class Config:
|
||||
self.rate_limits = {
|
||||
'crtsh': 5,
|
||||
'shodan': 60,
|
||||
'dns': 100
|
||||
'dns': 100,
|
||||
'correlation': 0 # Set to 0 to make sure correlations run last
|
||||
}
|
||||
|
||||
# --- Provider Settings ---
|
||||
self.enabled_providers = {
|
||||
'crtsh': True,
|
||||
'dns': True,
|
||||
'shodan': False
|
||||
'shodan': False,
|
||||
'correlation': True # Enable the new provider by default
|
||||
}
|
||||
|
||||
# --- Logging ---
|
||||
@@ -70,6 +75,9 @@ class Config:
|
||||
self.max_retries_per_target = int(os.getenv('MAX_RETRIES_PER_TARGET', self.max_retries_per_target))
|
||||
self.cache_timeout_hours = int(os.getenv('CACHE_TIMEOUT_HOURS', self.cache_timeout_hours))
|
||||
|
||||
# Override graph polling threshold from environment
|
||||
self.graph_polling_node_threshold = int(os.getenv('GRAPH_POLLING_NODE_THRESHOLD', self.graph_polling_node_threshold))
|
||||
|
||||
# Override Flask and session settings
|
||||
self.flask_host = os.getenv('FLASK_HOST', self.flask_host)
|
||||
self.flask_port = int(os.getenv('FLASK_PORT', self.flask_port))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Core modules for DNSRecon passive reconnaissance tool.
|
||||
Core modules for DNScope passive reconnaissance tool.
|
||||
Contains graph management, scanning orchestration, and forensic logging.
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# dnsrecon-reduced/core/graph_manager.py
|
||||
# DNScope-reduced/core/graph_manager.py
|
||||
|
||||
"""
|
||||
Graph data model for DNSRecon using NetworkX.
|
||||
Manages in-memory graph storage with confidence scoring and forensic metadata.
|
||||
Graph data model for DNScope using NetworkX.
|
||||
Manages in-memory graph storage with forensic metadata.
|
||||
Now fully compatible with the unified ProviderResult data model.
|
||||
UPDATED: Fixed correlation exclusion keys to match actual attribute names.
|
||||
UPDATED: Removed export_json() method - now handled by ExportManager.
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
@@ -29,8 +30,8 @@ class NodeType(Enum):
|
||||
|
||||
class GraphManager:
|
||||
"""
|
||||
Thread-safe graph manager for DNSRecon infrastructure mapping.
|
||||
Uses NetworkX for in-memory graph storage with confidence scoring.
|
||||
Thread-safe graph manager for DNScope infrastructure mapping.
|
||||
Uses NetworkX for in-memory graph storage.
|
||||
Compatible with unified ProviderResult data model.
|
||||
"""
|
||||
|
||||
@@ -39,270 +40,6 @@ class GraphManager:
|
||||
self.graph = nx.DiGraph()
|
||||
self.creation_time = datetime.now(timezone.utc).isoformat()
|
||||
self.last_modified = self.creation_time
|
||||
self.correlation_index = {}
|
||||
# Compile regex for date filtering for efficiency
|
||||
self.date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}')
|
||||
|
||||
# FIXED: Exclude cert_issuer_name since we already create proper CA relationships
|
||||
self.EXCLUDED_KEYS = [
|
||||
# Certificate metadata that creates noise or has dedicated node types
|
||||
'cert_source', # Always 'crtsh' for crtsh provider
|
||||
'cert_common_name',
|
||||
'cert_validity_period_days', # Numerical, not useful for correlation
|
||||
'cert_issuer_name', # FIXED: Has dedicated CA nodes, don't correlate
|
||||
#'cert_certificate_id', # Unique per certificate
|
||||
#'cert_serial_number', # Unique per certificate
|
||||
'cert_entry_timestamp', # Timestamp, filtered by date regex anyway
|
||||
'cert_not_before', # Date, filtered by date regex anyway
|
||||
'cert_not_after', # Date, filtered by date regex anyway
|
||||
# DNS metadata that creates noise
|
||||
'dns_ttl', # TTL values are not meaningful for correlation
|
||||
# Shodan metadata that might create noise
|
||||
'timestamp', # Generic timestamp fields
|
||||
'last_update', # Generic timestamp fields
|
||||
#'org', # Too generic, causes false correlations
|
||||
#'isp', # Too generic, causes false correlations
|
||||
# Generic noisy attributes
|
||||
'updated_timestamp', # Any timestamp field
|
||||
'discovery_timestamp', # Any timestamp field
|
||||
'query_timestamp', # Any timestamp field
|
||||
]
|
||||
|
||||
def __getstate__(self):
|
||||
"""Prepare GraphManager for pickling, excluding compiled regex."""
|
||||
state = self.__dict__.copy()
|
||||
# Compiled regex patterns are not always picklable
|
||||
if 'date_pattern' in state:
|
||||
del state['date_pattern']
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
"""Restore GraphManager state and recompile regex."""
|
||||
self.__dict__.update(state)
|
||||
self.date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}')
|
||||
|
||||
def process_correlations_for_node(self, node_id: str):
|
||||
"""
|
||||
UPDATED: Process correlations for a given node with enhanced tracking.
|
||||
Now properly tracks which attribute/provider created each correlation.
|
||||
"""
|
||||
if not self.graph.has_node(node_id):
|
||||
return
|
||||
|
||||
node_attributes = self.graph.nodes[node_id].get('attributes', [])
|
||||
|
||||
# Process each attribute for potential correlations
|
||||
for attr in node_attributes:
|
||||
attr_name = attr.get('name')
|
||||
attr_value = attr.get('value')
|
||||
attr_provider = attr.get('provider', 'unknown')
|
||||
|
||||
# IMPROVED: More comprehensive exclusion logic
|
||||
should_exclude = (
|
||||
# Check against excluded keys (exact match or substring)
|
||||
any(excluded_key in attr_name or attr_name == excluded_key for excluded_key in self.EXCLUDED_KEYS) or
|
||||
# Invalid value types
|
||||
not isinstance(attr_value, (str, int, float, bool)) or
|
||||
attr_value is None or
|
||||
# Boolean values are not useful for correlation
|
||||
isinstance(attr_value, bool) or
|
||||
# String values that are too short or are dates
|
||||
(isinstance(attr_value, str) and (
|
||||
len(attr_value) < 4 or
|
||||
self.date_pattern.match(attr_value) or
|
||||
# Exclude common generic values that create noise
|
||||
attr_value.lower() in ['unknown', 'none', 'null', 'n/a', 'true', 'false', '0', '1']
|
||||
)) or
|
||||
# Numerical values that are likely to be unique identifiers
|
||||
(isinstance(attr_value, (int, float)) and (
|
||||
attr_value == 0 or # Zero values are not meaningful
|
||||
attr_value == 1 or # One values are too common
|
||||
abs(attr_value) > 1000000 # Very large numbers are likely IDs
|
||||
))
|
||||
)
|
||||
|
||||
if should_exclude:
|
||||
continue
|
||||
|
||||
# Initialize correlation tracking for this value
|
||||
if attr_value not in self.correlation_index:
|
||||
self.correlation_index[attr_value] = {
|
||||
'nodes': set(),
|
||||
'sources': [] # Track which provider/attribute combinations contributed
|
||||
}
|
||||
|
||||
# Add this node and source information
|
||||
self.correlation_index[attr_value]['nodes'].add(node_id)
|
||||
|
||||
# Track the source of this correlation value
|
||||
source_info = {
|
||||
'node_id': node_id,
|
||||
'provider': attr_provider,
|
||||
'attribute': attr_name,
|
||||
'path': f"{attr_provider}_{attr_name}"
|
||||
}
|
||||
|
||||
# Add source if not already present (avoid duplicates)
|
||||
existing_sources = [s for s in self.correlation_index[attr_value]['sources']
|
||||
if s['node_id'] == node_id and s['path'] == source_info['path']]
|
||||
if not existing_sources:
|
||||
self.correlation_index[attr_value]['sources'].append(source_info)
|
||||
|
||||
# Create correlation node if we have multiple nodes with this value
|
||||
if len(self.correlation_index[attr_value]['nodes']) > 1:
|
||||
self._create_enhanced_correlation_node_and_edges(attr_value, self.correlation_index[attr_value])
|
||||
|
||||
def _create_enhanced_correlation_node_and_edges(self, value, correlation_data):
|
||||
"""
|
||||
UPDATED: Create correlation node and edges with raw provider data (no formatting).
|
||||
"""
|
||||
correlation_node_id = f"corr_{hash(str(value)) & 0x7FFFFFFF}"
|
||||
nodes = correlation_data['nodes']
|
||||
sources = correlation_data['sources']
|
||||
|
||||
# Create or update correlation node
|
||||
if not self.graph.has_node(correlation_node_id):
|
||||
# Use raw provider/attribute data - no formatting
|
||||
provider_counts = {}
|
||||
for source in sources:
|
||||
# Keep original provider and attribute names
|
||||
key = f"{source['provider']}_{source['attribute']}"
|
||||
provider_counts[key] = provider_counts.get(key, 0) + 1
|
||||
|
||||
# Use the most common provider/attribute as the primary label (raw)
|
||||
primary_source = max(provider_counts.items(), key=lambda x: x[1])[0] if provider_counts else "unknown_correlation"
|
||||
|
||||
metadata = {
|
||||
'value': value,
|
||||
'correlated_nodes': list(nodes),
|
||||
'sources': sources,
|
||||
'primary_source': primary_source,
|
||||
'correlation_count': len(nodes)
|
||||
}
|
||||
|
||||
self.add_node(correlation_node_id, NodeType.CORRELATION_OBJECT, metadata=metadata)
|
||||
#print(f"Created correlation node {correlation_node_id} for value '{value}' with {len(nodes)} nodes")
|
||||
|
||||
# Create edges from each node to the correlation node
|
||||
for source in sources:
|
||||
node_id = source['node_id']
|
||||
provider = source['provider']
|
||||
attribute = source['attribute']
|
||||
|
||||
if self.graph.has_node(node_id) and not self.graph.has_edge(node_id, correlation_node_id):
|
||||
# Format relationship label as "corr_provider_attribute"
|
||||
relationship_label = f"corr_{provider}_{attribute}"
|
||||
|
||||
self.add_edge(
|
||||
source_id=node_id,
|
||||
target_id=correlation_node_id,
|
||||
relationship_type=relationship_label,
|
||||
confidence_score=0.9,
|
||||
source_provider=provider,
|
||||
raw_data={
|
||||
'correlation_value': value,
|
||||
'original_attribute': attribute,
|
||||
'correlation_type': 'attribute_matching'
|
||||
}
|
||||
)
|
||||
|
||||
#print(f"Added correlation edge: {node_id} -> {correlation_node_id} ({relationship_label})")
|
||||
|
||||
|
||||
def _has_direct_edge_bidirectional(self, node_a: str, node_b: str) -> bool:
|
||||
"""
|
||||
Check if there's a direct edge between two nodes in either direction.
|
||||
Returns True if node_aâ†'node_b OR node_bâ†'node_a exists.
|
||||
"""
|
||||
return (self.graph.has_edge(node_a, node_b) or
|
||||
self.graph.has_edge(node_b, node_a))
|
||||
|
||||
def _correlation_value_matches_existing_node(self, correlation_value: str) -> bool:
|
||||
"""
|
||||
Check if correlation value contains any existing node ID as substring.
|
||||
Returns True if match found (correlation node should NOT be created).
|
||||
"""
|
||||
correlation_str = str(correlation_value).lower()
|
||||
|
||||
# Check against all existing nodes
|
||||
for existing_node_id in self.graph.nodes():
|
||||
if existing_node_id.lower() in correlation_str:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _find_correlation_nodes_with_same_pattern(self, node_set: set) -> List[str]:
|
||||
"""
|
||||
Find existing correlation nodes that have the exact same pattern of connected nodes.
|
||||
Returns list of correlation node IDs with matching patterns.
|
||||
"""
|
||||
correlation_nodes = self.get_nodes_by_type(NodeType.CORRELATION_OBJECT)
|
||||
matching_nodes = []
|
||||
|
||||
for corr_node_id in correlation_nodes:
|
||||
# Get all nodes connected to this correlation node
|
||||
connected_nodes = set()
|
||||
|
||||
# Add all predecessors (nodes pointing TO the correlation node)
|
||||
connected_nodes.update(self.graph.predecessors(corr_node_id))
|
||||
|
||||
# Add all successors (nodes pointed TO by the correlation node)
|
||||
connected_nodes.update(self.graph.successors(corr_node_id))
|
||||
|
||||
# Check if the pattern matches exactly
|
||||
if connected_nodes == node_set:
|
||||
matching_nodes.append(corr_node_id)
|
||||
|
||||
return matching_nodes
|
||||
|
||||
def _merge_correlation_values(self, target_node_id: str, new_value: Any, corr_data: Dict) -> None:
|
||||
"""
|
||||
Merge a new correlation value into an existing correlation node.
|
||||
Uses same logic as large entity merging.
|
||||
"""
|
||||
if not self.graph.has_node(target_node_id):
|
||||
return
|
||||
|
||||
target_metadata = self.graph.nodes[target_node_id]['metadata']
|
||||
|
||||
# Get existing values (ensure it's a list)
|
||||
existing_values = target_metadata.get('values', [])
|
||||
if not isinstance(existing_values, list):
|
||||
existing_values = [existing_values]
|
||||
|
||||
# Add new value if not already present
|
||||
if new_value not in existing_values:
|
||||
existing_values.append(new_value)
|
||||
|
||||
# Merge sources
|
||||
existing_sources = target_metadata.get('sources', [])
|
||||
new_sources = corr_data.get('sources', [])
|
||||
|
||||
# Create set of unique sources based on (node_id, path) tuples
|
||||
source_set = set()
|
||||
for source in existing_sources + new_sources:
|
||||
source_tuple = (source['node_id'], source.get('path', ''))
|
||||
source_set.add(source_tuple)
|
||||
|
||||
# Convert back to list of dictionaries
|
||||
merged_sources = [{'node_id': nid, 'path': path} for nid, path in source_set]
|
||||
|
||||
# Update metadata
|
||||
target_metadata.update({
|
||||
'values': existing_values,
|
||||
'sources': merged_sources,
|
||||
'correlated_nodes': list(set(target_metadata.get('correlated_nodes', []) + corr_data.get('nodes', []))),
|
||||
'merge_count': len(existing_values),
|
||||
'last_merge_timestamp': datetime.now(timezone.utc).isoformat()
|
||||
})
|
||||
|
||||
# Update description to reflect merged nature
|
||||
value_count = len(existing_values)
|
||||
node_count = len(target_metadata['correlated_nodes'])
|
||||
self.graph.nodes[target_node_id]['description'] = (
|
||||
f"Correlation container with {value_count} merged values "
|
||||
f"across {node_count} nodes"
|
||||
)
|
||||
|
||||
def add_node(self, node_id: str, node_type: NodeType, attributes: Optional[List[Dict[str, Any]]] = None,
|
||||
description: str = "", metadata: Optional[Dict[str, Any]] = None) -> bool:
|
||||
@@ -346,7 +83,7 @@ class GraphManager:
|
||||
return is_new_node
|
||||
|
||||
def add_edge(self, source_id: str, target_id: str, relationship_type: str,
|
||||
confidence_score: float = 0.5, source_provider: str = "unknown",
|
||||
source_provider: str = "unknown",
|
||||
raw_data: Optional[Dict[str, Any]] = None) -> bool:
|
||||
"""
|
||||
UPDATED: Add or update an edge between two nodes with raw relationship labels.
|
||||
@@ -354,59 +91,19 @@ class GraphManager:
|
||||
if not self.graph.has_node(source_id) or not self.graph.has_node(target_id):
|
||||
return False
|
||||
|
||||
new_confidence = confidence_score
|
||||
|
||||
# UPDATED: Use raw relationship type - no formatting
|
||||
edge_label = relationship_type
|
||||
|
||||
if self.graph.has_edge(source_id, target_id):
|
||||
# If edge exists, update confidence if the new score is higher.
|
||||
if new_confidence > self.graph.edges[source_id, target_id].get('confidence_score', 0):
|
||||
self.graph.edges[source_id, target_id]['confidence_score'] = new_confidence
|
||||
self.graph.edges[source_id, target_id]['updated_timestamp'] = datetime.now(timezone.utc).isoformat()
|
||||
self.graph.edges[source_id, target_id]['updated_by'] = source_provider
|
||||
return False
|
||||
|
||||
# Add a new edge with raw attributes
|
||||
self.graph.add_edge(source_id, target_id,
|
||||
relationship_type=edge_label,
|
||||
confidence_score=new_confidence,
|
||||
source_provider=source_provider,
|
||||
discovery_timestamp=datetime.now(timezone.utc).isoformat(),
|
||||
raw_data=raw_data or {})
|
||||
self.last_modified = datetime.now(timezone.utc).isoformat()
|
||||
return True
|
||||
|
||||
def extract_node_from_large_entity(self, large_entity_id: str, node_id_to_extract: str) -> bool:
|
||||
"""
|
||||
Removes a node from a large entity's internal lists and updates its count.
|
||||
This prepares the large entity for the node's promotion to a regular node.
|
||||
"""
|
||||
if not self.graph.has_node(large_entity_id):
|
||||
return False
|
||||
|
||||
node_data = self.graph.nodes[large_entity_id]
|
||||
attributes = node_data.get('attributes', [])
|
||||
|
||||
# Find the 'nodes' attribute dictionary in the list
|
||||
nodes_attr = next((attr for attr in attributes if attr.get('name') == 'nodes'), None)
|
||||
|
||||
# Remove from the list of member nodes
|
||||
if nodes_attr and 'value' in nodes_attr and isinstance(nodes_attr['value'], list) and node_id_to_extract in nodes_attr['value']:
|
||||
nodes_attr['value'].remove(node_id_to_extract)
|
||||
|
||||
# Find the 'count' attribute and update it
|
||||
count_attr = next((attr for attr in attributes if attr.get('name') == 'count'), None)
|
||||
if count_attr:
|
||||
count_attr['value'] = len(nodes_attr['value'])
|
||||
else:
|
||||
# This can happen if the node was already extracted, which is not an error.
|
||||
print(f"Warning: Node {node_id_to_extract} not found in the 'nodes' list of {large_entity_id}.")
|
||||
return True # Proceed as if successful
|
||||
|
||||
self.last_modified = datetime.now(timezone.utc).isoformat()
|
||||
return True
|
||||
|
||||
def remove_node(self, node_id: str) -> bool:
|
||||
"""Remove a node and its connected edges from the graph."""
|
||||
if not self.graph.has_node(node_id):
|
||||
@@ -415,28 +112,6 @@ class GraphManager:
|
||||
# Remove node from the graph (NetworkX handles removing connected edges)
|
||||
self.graph.remove_node(node_id)
|
||||
|
||||
# Clean up the correlation index
|
||||
keys_to_delete = []
|
||||
for value, data in self.correlation_index.items():
|
||||
if isinstance(data, dict) and 'nodes' in data:
|
||||
# Updated correlation structure
|
||||
if node_id in data['nodes']:
|
||||
data['nodes'].discard(node_id)
|
||||
# Remove sources for this node
|
||||
data['sources'] = [s for s in data['sources'] if s['node_id'] != node_id]
|
||||
if not data['nodes']: # If no other nodes are associated, remove it
|
||||
keys_to_delete.append(value)
|
||||
else:
|
||||
# Legacy correlation structure (fallback)
|
||||
if isinstance(data, set) and node_id in data:
|
||||
data.discard(node_id)
|
||||
if not data:
|
||||
keys_to_delete.append(value)
|
||||
|
||||
for key in keys_to_delete:
|
||||
if key in self.correlation_index:
|
||||
del self.correlation_index[key]
|
||||
|
||||
self.last_modified = datetime.now(timezone.utc).isoformat()
|
||||
return True
|
||||
|
||||
@@ -452,11 +127,6 @@ class GraphManager:
|
||||
"""Get all nodes of a specific type."""
|
||||
return [n for n, d in self.graph.nodes(data=True) if d.get('type') == node_type.value]
|
||||
|
||||
def get_high_confidence_edges(self, min_confidence: float = 0.8) -> List[Tuple[str, str, Dict]]:
|
||||
"""Get edges with confidence score above a given threshold."""
|
||||
return [(u, v, d) for u, v, d in self.graph.edges(data=True)
|
||||
if d.get('confidence_score', 0) >= min_confidence]
|
||||
|
||||
def get_graph_data(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Export graph data formatted for frontend visualization.
|
||||
@@ -471,7 +141,8 @@ class GraphManager:
|
||||
'attributes': attrs.get('attributes', []), # Raw attributes list
|
||||
'description': attrs.get('description', ''),
|
||||
'metadata': attrs.get('metadata', {}),
|
||||
'added_timestamp': attrs.get('added_timestamp')
|
||||
'added_timestamp': attrs.get('added_timestamp'),
|
||||
'max_depth_reached': attrs.get('metadata', {}).get('max_depth_reached', False)
|
||||
}
|
||||
|
||||
# Add incoming and outgoing edges to node data
|
||||
@@ -491,9 +162,9 @@ class GraphManager:
|
||||
'from': source,
|
||||
'to': target,
|
||||
'label': attrs.get('relationship_type', ''),
|
||||
'confidence_score': attrs.get('confidence_score', 0),
|
||||
'source_provider': attrs.get('source_provider', ''),
|
||||
'discovery_timestamp': attrs.get('discovery_timestamp')
|
||||
'discovery_timestamp': attrs.get('discovery_timestamp'),
|
||||
'raw_data': attrs.get('raw_data', {})
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -502,40 +173,6 @@ class GraphManager:
|
||||
'statistics': self.get_statistics()['basic_metrics']
|
||||
}
|
||||
|
||||
def export_json(self) -> Dict[str, Any]:
|
||||
"""Export complete graph data as a JSON-serializable dictionary."""
|
||||
graph_data = nx.node_link_data(self.graph, edges="edges")
|
||||
return {
|
||||
'export_metadata': {
|
||||
'export_timestamp': datetime.now(timezone.utc).isoformat(),
|
||||
'graph_creation_time': self.creation_time,
|
||||
'last_modified': self.last_modified,
|
||||
'total_nodes': self.get_node_count(),
|
||||
'total_edges': self.get_edge_count(),
|
||||
'graph_format': 'dnsrecon_v1_unified_model'
|
||||
},
|
||||
'graph': graph_data,
|
||||
'statistics': self.get_statistics()
|
||||
}
|
||||
|
||||
def _get_confidence_distribution(self) -> Dict[str, int]:
|
||||
"""Get distribution of edge confidence scores with empty graph handling."""
|
||||
distribution = {'high': 0, 'medium': 0, 'low': 0}
|
||||
|
||||
# FIXED: Handle empty graph case
|
||||
if self.get_edge_count() == 0:
|
||||
return distribution
|
||||
|
||||
for _, _, data in self.graph.edges(data=True):
|
||||
confidence = data.get('confidence_score', 0)
|
||||
if confidence >= 0.8:
|
||||
distribution['high'] += 1
|
||||
elif confidence >= 0.6:
|
||||
distribution['medium'] += 1
|
||||
else:
|
||||
distribution['low'] += 1
|
||||
return distribution
|
||||
|
||||
def get_statistics(self) -> Dict[str, Any]:
|
||||
"""Get comprehensive statistics about the graph with proper empty graph handling."""
|
||||
|
||||
@@ -552,7 +189,6 @@ class GraphManager:
|
||||
},
|
||||
'node_type_distribution': {},
|
||||
'relationship_type_distribution': {},
|
||||
'confidence_distribution': self._get_confidence_distribution(),
|
||||
'provider_distribution': {}
|
||||
}
|
||||
|
||||
@@ -576,8 +212,7 @@ class GraphManager:
|
||||
return stats
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all nodes, edges, and indices from the graph."""
|
||||
"""Clear all nodes and edges from the graph."""
|
||||
self.graph.clear()
|
||||
self.correlation_index.clear()
|
||||
self.creation_time = datetime.now(timezone.utc).isoformat()
|
||||
self.last_modified = self.creation_time
|
||||
@@ -1,4 +1,4 @@
|
||||
# dnsrecon/core/logger.py
|
||||
# DNScope/core/logger.py
|
||||
|
||||
import logging
|
||||
import threading
|
||||
@@ -30,7 +30,6 @@ class RelationshipDiscovery:
|
||||
source_node: str
|
||||
target_node: str
|
||||
relationship_type: str
|
||||
confidence_score: float
|
||||
provider: str
|
||||
raw_data: Dict[str, Any]
|
||||
discovery_method: str
|
||||
@@ -38,7 +37,7 @@ class RelationshipDiscovery:
|
||||
|
||||
class ForensicLogger:
|
||||
"""
|
||||
Thread-safe forensic logging system for DNSRecon.
|
||||
Thread-safe forensic logging system for DNScope.
|
||||
Maintains detailed audit trail of all reconnaissance activities.
|
||||
"""
|
||||
|
||||
@@ -66,7 +65,7 @@ class ForensicLogger:
|
||||
}
|
||||
|
||||
# Configure standard logger
|
||||
self.logger = logging.getLogger(f'dnsrecon.{self.session_id}')
|
||||
self.logger = logging.getLogger(f'DNScope.{self.session_id}')
|
||||
self.logger.setLevel(logging.INFO)
|
||||
|
||||
# Create formatter for structured logging
|
||||
@@ -94,7 +93,7 @@ class ForensicLogger:
|
||||
"""Restore ForensicLogger after unpickling by reconstructing logger."""
|
||||
self.__dict__.update(state)
|
||||
# Re-initialize the 'logger' attribute
|
||||
self.logger = logging.getLogger(f'dnsrecon.{self.session_id}')
|
||||
self.logger = logging.getLogger(f'DNScope.{self.session_id}')
|
||||
self.logger.setLevel(logging.INFO)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
@@ -107,7 +106,7 @@ class ForensicLogger:
|
||||
|
||||
def _generate_session_id(self) -> str:
|
||||
"""Generate unique session identifier."""
|
||||
return f"dnsrecon_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
return f"DNScope_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
def log_api_request(self, provider: str, url: str, method: str = "GET",
|
||||
status_code: Optional[int] = None,
|
||||
@@ -157,7 +156,7 @@ class ForensicLogger:
|
||||
self.logger.info(f"API Request - {provider}: {url} - Status: {status_code}")
|
||||
|
||||
def log_relationship_discovery(self, source_node: str, target_node: str,
|
||||
relationship_type: str, confidence_score: float,
|
||||
relationship_type: str,
|
||||
provider: str, raw_data: Dict[str, Any],
|
||||
discovery_method: str) -> None:
|
||||
"""
|
||||
@@ -167,7 +166,6 @@ class ForensicLogger:
|
||||
source_node: Source node identifier
|
||||
target_node: Target node identifier
|
||||
relationship_type: Type of relationship (e.g., 'SAN', 'A_Record')
|
||||
confidence_score: Confidence score (0.0 to 1.0)
|
||||
provider: Provider that discovered this relationship
|
||||
raw_data: Raw data from provider response
|
||||
discovery_method: Method used to discover relationship
|
||||
@@ -177,7 +175,6 @@ class ForensicLogger:
|
||||
source_node=source_node,
|
||||
target_node=target_node,
|
||||
relationship_type=relationship_type,
|
||||
confidence_score=confidence_score,
|
||||
provider=provider,
|
||||
raw_data=raw_data,
|
||||
discovery_method=discovery_method
|
||||
@@ -188,7 +185,7 @@ class ForensicLogger:
|
||||
|
||||
self.logger.info(
|
||||
f"Relationship Discovered - {source_node} -> {target_node} "
|
||||
f"({relationship_type}) - Confidence: {confidence_score:.2f} - Provider: {provider}"
|
||||
f"({relationship_type}) - Provider: {provider}"
|
||||
)
|
||||
|
||||
def log_scan_start(self, target_domain: str, recursion_depth: int,
|
||||
@@ -197,13 +194,11 @@ class ForensicLogger:
|
||||
self.logger.info(f"Scan Started - Target: {target_domain}, Depth: {recursion_depth}")
|
||||
self.logger.info(f"Enabled Providers: {', '.join(enabled_providers)}")
|
||||
|
||||
self.session_metadata['target_domains'].update(target_domain)
|
||||
self.session_metadata['target_domains'].add(target_domain)
|
||||
|
||||
def log_scan_complete(self) -> None:
|
||||
"""Log the completion of a reconnaissance scan."""
|
||||
self.session_metadata['end_time'] = datetime.now(timezone.utc).isoformat()
|
||||
self.session_metadata['providers_used'] = list(self.session_metadata['providers_used'])
|
||||
self.session_metadata['target_domains'] = list(self.session_metadata['target_domains'])
|
||||
|
||||
self.logger.info(f"Scan Complete - Session: {self.session_id}")
|
||||
|
||||
@@ -214,8 +209,12 @@ class ForensicLogger:
|
||||
Returns:
|
||||
Dictionary containing complete session audit trail
|
||||
"""
|
||||
session_metadata_export = self.session_metadata.copy()
|
||||
session_metadata_export['providers_used'] = list(session_metadata_export['providers_used'])
|
||||
session_metadata_export['target_domains'] = list(session_metadata_export['target_domains'])
|
||||
|
||||
return {
|
||||
'session_metadata': self.session_metadata.copy(),
|
||||
'session_metadata': session_metadata_export,
|
||||
'api_requests': [asdict(req) for req in self.api_requests],
|
||||
'relationships': [asdict(rel) for rel in self.relationships],
|
||||
'export_timestamp': datetime.now(timezone.utc).isoformat()
|
||||
@@ -238,7 +237,6 @@ class ForensicLogger:
|
||||
'successful_requests': len([req for req in provider_requests if req.error is None]),
|
||||
'failed_requests': len([req for req in provider_requests if req.error is not None]),
|
||||
'relationships_discovered': len(provider_relationships),
|
||||
'avg_confidence': sum(rel.confidence_score for rel in provider_relationships) / len(provider_relationships) if provider_relationships else 0
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# dnsrecon-reduced/core/provider_result.py
|
||||
# DNScope-reduced/core/provider_result.py
|
||||
|
||||
"""
|
||||
Unified data model for DNSRecon passive reconnaissance.
|
||||
Unified data model for DNScope passive reconnaissance.
|
||||
Standardizes the data structure across all providers to ensure consistent processing.
|
||||
"""
|
||||
|
||||
@@ -18,33 +18,19 @@ class StandardAttribute:
|
||||
value: Any
|
||||
type: str
|
||||
provider: str
|
||||
confidence: float
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
metadata: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate the attribute after initialization."""
|
||||
if not isinstance(self.confidence, (int, float)) or not 0.0 <= self.confidence <= 1.0:
|
||||
raise ValueError(f"Confidence must be between 0.0 and 1.0, got {self.confidence}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Relationship:
|
||||
"""A unified data structure for a directional link between two nodes."""
|
||||
source_node: str
|
||||
target_node: str
|
||||
relationship_type: str
|
||||
confidence: float
|
||||
provider: str
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
raw_data: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate the relationship after initialization."""
|
||||
if not isinstance(self.confidence, (int, float)) or not 0.0 <= self.confidence <= 1.0:
|
||||
raise ValueError(f"Confidence must be between 0.0 and 1.0, got {self.confidence}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProviderResult:
|
||||
"""A container for all data returned by a provider from a single query."""
|
||||
@@ -52,8 +38,7 @@ class ProviderResult:
|
||||
relationships: List[Relationship] = field(default_factory=list)
|
||||
|
||||
def add_attribute(self, target_node: str, name: str, value: Any, attr_type: str,
|
||||
provider: str, confidence: float = 0.8,
|
||||
metadata: Optional[Dict[str, Any]] = None) -> None:
|
||||
provider: str, metadata: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""Helper method to add an attribute to the result."""
|
||||
self.attributes.append(StandardAttribute(
|
||||
target_node=target_node,
|
||||
@@ -61,19 +46,16 @@ class ProviderResult:
|
||||
value=value,
|
||||
type=attr_type,
|
||||
provider=provider,
|
||||
confidence=confidence,
|
||||
metadata=metadata or {}
|
||||
))
|
||||
|
||||
def add_relationship(self, source_node: str, target_node: str, relationship_type: str,
|
||||
provider: str, confidence: float = 0.8,
|
||||
raw_data: Optional[Dict[str, Any]] = None) -> None:
|
||||
provider: str, raw_data: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""Helper method to add a relationship to the result."""
|
||||
self.relationships.append(Relationship(
|
||||
source_node=source_node,
|
||||
target_node=target_node,
|
||||
relationship_type=relationship_type,
|
||||
confidence=confidence,
|
||||
provider=provider,
|
||||
raw_data=raw_data or {}
|
||||
))
|
||||
|
||||
@@ -1,28 +1,145 @@
|
||||
# dnsrecon-reduced/core/rate_limiter.py
|
||||
# DNScope-reduced/core/rate_limiter.py
|
||||
|
||||
import time
|
||||
import logging
|
||||
|
||||
class GlobalRateLimiter:
|
||||
"""
|
||||
FIXED: Improved rate limiter with better cleanup and error handling.
|
||||
Prevents accumulation of stale entries that cause infinite retry loops.
|
||||
"""
|
||||
|
||||
def __init__(self, redis_client):
|
||||
self.redis = redis_client
|
||||
self.logger = logging.getLogger('DNScope.rate_limiter')
|
||||
# Track last cleanup times to avoid excessive Redis operations
|
||||
self._last_cleanup = {}
|
||||
|
||||
def is_rate_limited(self, key, limit, period):
|
||||
"""
|
||||
Check if a key is rate-limited.
|
||||
FIXED: Check if a key is rate-limited with improved cleanup and error handling.
|
||||
|
||||
Args:
|
||||
key: Rate limit key (e.g., provider name)
|
||||
limit: Maximum requests allowed
|
||||
period: Time period in seconds (60 for per-minute)
|
||||
|
||||
Returns:
|
||||
bool: True if rate limited, False otherwise
|
||||
"""
|
||||
if limit <= 0:
|
||||
# Rate limit of 0 or negative means no limiting
|
||||
return False
|
||||
|
||||
now = time.time()
|
||||
key = f"rate_limit:{key}"
|
||||
rate_key = f"rate_limit:{key}"
|
||||
|
||||
# Remove old timestamps
|
||||
self.redis.zremrangebyscore(key, 0, now - period)
|
||||
try:
|
||||
# FIXED: More aggressive cleanup to prevent accumulation
|
||||
# Only clean up if we haven't cleaned recently (every 10 seconds max)
|
||||
should_cleanup = (
|
||||
rate_key not in self._last_cleanup or
|
||||
now - self._last_cleanup.get(rate_key, 0) > 10
|
||||
)
|
||||
|
||||
# Check the count
|
||||
count = self.redis.zcard(key)
|
||||
if count >= limit:
|
||||
if should_cleanup:
|
||||
# Remove entries older than the period
|
||||
removed_count = self.redis.zremrangebyscore(rate_key, 0, now - period)
|
||||
self._last_cleanup[rate_key] = now
|
||||
|
||||
if removed_count > 0:
|
||||
self.logger.debug(f"Rate limiter cleaned up {removed_count} old entries for {key}")
|
||||
|
||||
# Get current count
|
||||
current_count = self.redis.zcard(rate_key)
|
||||
|
||||
if current_count >= limit:
|
||||
self.logger.debug(f"Rate limited: {key} has {current_count}/{limit} requests in period")
|
||||
return True
|
||||
|
||||
# Add new timestamp
|
||||
self.redis.zadd(key, {now: now})
|
||||
self.redis.expire(key, period)
|
||||
# Add new timestamp with error handling
|
||||
try:
|
||||
# Use pipeline for atomic operations
|
||||
pipe = self.redis.pipeline()
|
||||
pipe.zadd(rate_key, {str(now): now})
|
||||
pipe.expire(rate_key, int(period * 2)) # Set TTL to 2x period for safety
|
||||
pipe.execute()
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to record rate limit entry for {key}: {e}")
|
||||
# Don't block the request if we can't record it
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Rate limiter error for {key}: {e}")
|
||||
# FIXED: On Redis errors, don't block requests to avoid infinite loops
|
||||
return False
|
||||
|
||||
def get_rate_limit_status(self, key, limit, period):
|
||||
"""
|
||||
Get detailed rate limit status for debugging.
|
||||
|
||||
Returns:
|
||||
dict: Status information including current count, limit, and time to reset
|
||||
"""
|
||||
now = time.time()
|
||||
rate_key = f"rate_limit:{key}"
|
||||
|
||||
try:
|
||||
current_count = self.redis.zcard(rate_key)
|
||||
|
||||
# Get oldest entry to calculate reset time
|
||||
oldest_entries = self.redis.zrange(rate_key, 0, 0, withscores=True)
|
||||
time_to_reset = 0
|
||||
if oldest_entries:
|
||||
oldest_time = oldest_entries[0][1]
|
||||
time_to_reset = max(0, period - (now - oldest_time))
|
||||
|
||||
return {
|
||||
'key': key,
|
||||
'current_count': current_count,
|
||||
'limit': limit,
|
||||
'period': period,
|
||||
'is_limited': current_count >= limit,
|
||||
'time_to_reset': time_to_reset
|
||||
}
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to get rate limit status for {key}: {e}")
|
||||
return {
|
||||
'key': key,
|
||||
'current_count': 0,
|
||||
'limit': limit,
|
||||
'period': period,
|
||||
'is_limited': False,
|
||||
'time_to_reset': 0,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def reset_rate_limit(self, key):
|
||||
"""
|
||||
ADDED: Reset rate limit for a specific key (useful for debugging).
|
||||
"""
|
||||
rate_key = f"rate_limit:{key}"
|
||||
try:
|
||||
deleted = self.redis.delete(rate_key)
|
||||
self.logger.info(f"Reset rate limit for {key} (deleted: {deleted})")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to reset rate limit for {key}: {e}")
|
||||
return False
|
||||
|
||||
def cleanup_all_rate_limits(self):
|
||||
"""
|
||||
ADDED: Clean up all rate limit entries (useful for maintenance).
|
||||
"""
|
||||
try:
|
||||
keys = self.redis.keys("rate_limit:*")
|
||||
if keys:
|
||||
deleted = self.redis.delete(*keys)
|
||||
self.logger.info(f"Cleaned up {deleted} rate limit keys")
|
||||
return deleted
|
||||
return 0
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to cleanup rate limits: {e}")
|
||||
return 0
|
||||
977
core/scanner.py
977
core/scanner.py
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Per-session configuration management for DNSRecon.
|
||||
Per-session configuration management for DNScope.
|
||||
Provides isolated configuration instances for each user session.
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# dnsrecon/core/session_manager.py
|
||||
# DNScope/core/session_manager.py
|
||||
|
||||
import threading
|
||||
import time
|
||||
@@ -58,11 +58,11 @@ class SessionManager:
|
||||
|
||||
def _get_session_key(self, session_id: str) -> str:
|
||||
"""Generates the Redis key for a session."""
|
||||
return f"dnsrecon:session:{session_id}"
|
||||
return f"DNScope:session:{session_id}"
|
||||
|
||||
def _get_stop_signal_key(self, session_id: str) -> str:
|
||||
"""Generates the Redis key for a session's stop signal."""
|
||||
return f"dnsrecon:stop:{session_id}"
|
||||
return f"DNScope:stop:{session_id}"
|
||||
|
||||
def create_session(self) -> str:
|
||||
"""
|
||||
@@ -353,7 +353,7 @@ class SessionManager:
|
||||
while True:
|
||||
try:
|
||||
# Clean up orphaned stop signals
|
||||
stop_keys = self.redis_client.keys("dnsrecon:stop:*")
|
||||
stop_keys = self.redis_client.keys("DNScope:stop:*")
|
||||
for stop_key in stop_keys:
|
||||
# Extract session ID from stop key
|
||||
session_id = stop_key.decode('utf-8').split(':')[-1]
|
||||
@@ -372,8 +372,8 @@ class SessionManager:
|
||||
def get_statistics(self) -> Dict[str, Any]:
|
||||
"""Get session manager statistics."""
|
||||
try:
|
||||
session_keys = self.redis_client.keys("dnsrecon:session:*")
|
||||
stop_keys = self.redis_client.keys("dnsrecon:stop:*")
|
||||
session_keys = self.redis_client.keys("DNScope:session:*")
|
||||
stop_keys = self.redis_client.keys("DNScope:stop:*")
|
||||
|
||||
active_sessions = len(session_keys)
|
||||
running_scans = 0
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Data provider modules for DNSRecon.
|
||||
Data provider modules for DNScope.
|
||||
Contains implementations for various reconnaissance data sources.
|
||||
"""
|
||||
|
||||
@@ -7,6 +7,7 @@ from .base_provider import BaseProvider
|
||||
from .crtsh_provider import CrtShProvider
|
||||
from .dns_provider import DNSProvider
|
||||
from .shodan_provider import ShodanProvider
|
||||
from .correlation_provider import CorrelationProvider
|
||||
from core.rate_limiter import GlobalRateLimiter
|
||||
|
||||
__all__ = [
|
||||
@@ -14,7 +15,8 @@ __all__ = [
|
||||
'GlobalRateLimiter',
|
||||
'CrtShProvider',
|
||||
'DNSProvider',
|
||||
'ShodanProvider'
|
||||
'ShodanProvider',
|
||||
'CorrelationProvider'
|
||||
]
|
||||
|
||||
__version__ = "0.0.0-rc"
|
||||
@@ -1,4 +1,4 @@
|
||||
# dnsrecon/providers/base_provider.py
|
||||
# DNScope/providers/base_provider.py
|
||||
|
||||
import time
|
||||
import requests
|
||||
@@ -6,14 +6,14 @@ import threading
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from core.logger import get_forensic_logger
|
||||
from core.logger import get_forensic_logger # Ensure this import is present
|
||||
from core.rate_limiter import GlobalRateLimiter
|
||||
from core.provider_result import ProviderResult
|
||||
|
||||
|
||||
class BaseProvider(ABC):
|
||||
"""
|
||||
Abstract base class for all DNSRecon data providers.
|
||||
Abstract base class for all DNScope data providers.
|
||||
Now supports session-specific configuration and returns standardized ProviderResult objects.
|
||||
"""
|
||||
|
||||
@@ -41,7 +41,6 @@ class BaseProvider(ABC):
|
||||
self.name = name
|
||||
self.timeout = actual_timeout
|
||||
self._local = threading.local()
|
||||
self.logger = get_forensic_logger()
|
||||
self._stop_event = None
|
||||
|
||||
# Statistics (per provider instance)
|
||||
@@ -72,10 +71,15 @@ class BaseProvider(ABC):
|
||||
if not hasattr(self._local, 'session'):
|
||||
self._local.session = requests.Session()
|
||||
self._local.session.headers.update({
|
||||
'User-Agent': 'DNSRecon/1.0 (Passive Reconnaissance Tool)'
|
||||
'User-Agent': 'DNScope/1.0 (Passive Reconnaissance Tool)'
|
||||
})
|
||||
return self._local.session
|
||||
|
||||
@property
|
||||
def logger(self):
|
||||
"""Get the current forensic logger instance."""
|
||||
return get_forensic_logger()
|
||||
|
||||
@abstractmethod
|
||||
def get_name(self) -> str:
|
||||
"""Return the provider name."""
|
||||
@@ -229,7 +233,6 @@ class BaseProvider(ABC):
|
||||
|
||||
def log_relationship_discovery(self, source_node: str, target_node: str,
|
||||
relationship_type: str,
|
||||
confidence_score: float,
|
||||
raw_data: Dict[str, Any],
|
||||
discovery_method: str) -> None:
|
||||
"""
|
||||
@@ -239,7 +242,6 @@ class BaseProvider(ABC):
|
||||
source_node: Source node identifier
|
||||
target_node: Target node identifier
|
||||
relationship_type: Type of relationship
|
||||
confidence_score: Confidence score
|
||||
raw_data: Raw data from provider
|
||||
discovery_method: Method used for discovery
|
||||
"""
|
||||
@@ -249,7 +251,6 @@ class BaseProvider(ABC):
|
||||
source_node=source_node,
|
||||
target_node=target_node,
|
||||
relationship_type=relationship_type,
|
||||
confidence_score=confidence_score,
|
||||
provider=self.name,
|
||||
raw_data=raw_data,
|
||||
discovery_method=discovery_method
|
||||
|
||||
283
providers/correlation_provider.py
Normal file
283
providers/correlation_provider.py
Normal file
@@ -0,0 +1,283 @@
|
||||
# dnsrecon-reduced/providers/correlation_provider.py
|
||||
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .base_provider import BaseProvider
|
||||
from core.provider_result import ProviderResult
|
||||
from core.graph_manager import NodeType, GraphManager
|
||||
|
||||
class CorrelationProvider(BaseProvider):
|
||||
"""
|
||||
A provider that finds correlations between nodes in the graph.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
|
||||
def __init__(self, name: str = "correlation", session_config=None):
|
||||
"""
|
||||
Initialize the correlation provider.
|
||||
"""
|
||||
super().__init__(name, session_config=session_config)
|
||||
self.graph: GraphManager | None = None
|
||||
self.correlation_index = {}
|
||||
self.date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}')
|
||||
self.EXCLUDED_KEYS = [
|
||||
'cert_source',
|
||||
'a_records',
|
||||
'mx_records',
|
||||
'ns_records',
|
||||
'ptr_records',
|
||||
'cert_issuer_ca_id',
|
||||
'cert_common_name',
|
||||
'cert_validity_period_days',
|
||||
'cert_issuer_name',
|
||||
'cert_entry_timestamp',
|
||||
'cert_serial_number', # useless
|
||||
'cert_not_before',
|
||||
'cert_not_after',
|
||||
'dns_ttl',
|
||||
'timestamp',
|
||||
'last_update',
|
||||
'updated_timestamp',
|
||||
'discovery_timestamp',
|
||||
'query_timestamp',
|
||||
'shodan_ip_str',
|
||||
'shodan_a_record',
|
||||
]
|
||||
|
||||
def get_name(self) -> str:
|
||||
"""Return the provider name."""
|
||||
return "correlation"
|
||||
|
||||
def get_display_name(self) -> str:
|
||||
"""Return the provider display name for the UI."""
|
||||
return "Correlation Engine"
|
||||
|
||||
def requires_api_key(self) -> bool:
|
||||
"""Return True if the provider requires an API key."""
|
||||
return False
|
||||
|
||||
def get_eligibility(self) -> Dict[str, bool]:
|
||||
"""Return a dictionary indicating if the provider can query domains and/or IPs."""
|
||||
return {'domains': True, 'ips': True}
|
||||
|
||||
def is_available(self) -> bool:
|
||||
"""Check if the provider is available and properly configured."""
|
||||
return True
|
||||
|
||||
def query_domain(self, domain: str) -> ProviderResult:
|
||||
"""
|
||||
Query the provider for information about a domain.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
return self._find_correlations(domain)
|
||||
|
||||
def query_ip(self, ip: str) -> ProviderResult:
|
||||
"""
|
||||
Query the provider for information about an IP address.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
return self._find_correlations(ip)
|
||||
|
||||
def set_graph_manager(self, graph_manager: GraphManager):
|
||||
"""
|
||||
Set the graph manager for the provider to use.
|
||||
"""
|
||||
self.graph = graph_manager
|
||||
|
||||
def _find_correlations(self, node_id: str) -> ProviderResult:
|
||||
"""
|
||||
Find correlations for a given node with enhanced filtering and error handling.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring and list value processing.
|
||||
"""
|
||||
result = ProviderResult()
|
||||
discovery_time = datetime.now(timezone.utc)
|
||||
|
||||
# Enhanced safety checks
|
||||
if not self.graph or not self.graph.graph.has_node(node_id):
|
||||
return result
|
||||
|
||||
try:
|
||||
node_attributes = self.graph.graph.nodes[node_id].get('attributes', [])
|
||||
|
||||
# Ensure attributes is a list (handle legacy data)
|
||||
if not isinstance(node_attributes, list):
|
||||
return result
|
||||
|
||||
correlations_found = 0
|
||||
|
||||
for attr in node_attributes:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
|
||||
attr_name = attr.get('name', '')
|
||||
attr_value = attr.get('value')
|
||||
attr_provider = attr.get('provider', 'unknown')
|
||||
|
||||
# Prepare a list of values to iterate over
|
||||
values_to_process = []
|
||||
if isinstance(attr_value, list):
|
||||
values_to_process.extend(attr_value)
|
||||
else:
|
||||
values_to_process.append(attr_value)
|
||||
|
||||
for value_item in values_to_process:
|
||||
# Enhanced filtering logic
|
||||
should_exclude = self._should_exclude_attribute(attr_name, value_item)
|
||||
|
||||
if should_exclude:
|
||||
continue
|
||||
|
||||
# Build correlation index
|
||||
if value_item not in self.correlation_index:
|
||||
self.correlation_index[value_item] = {
|
||||
'nodes': set(),
|
||||
'sources': []
|
||||
}
|
||||
|
||||
self.correlation_index[value_item]['nodes'].add(node_id)
|
||||
|
||||
source_info = {
|
||||
'node_id': node_id,
|
||||
'provider': attr_provider,
|
||||
'attribute': attr_name,
|
||||
'path': f"{attr_provider}_{attr_name}"
|
||||
}
|
||||
|
||||
# Avoid duplicate sources
|
||||
existing_sources = [s for s in self.correlation_index[value_item]['sources']
|
||||
if s['node_id'] == node_id and s['path'] == source_info['path']]
|
||||
if not existing_sources:
|
||||
self.correlation_index[value_item]['sources'].append(source_info)
|
||||
|
||||
# Create correlation if we have multiple nodes with this value
|
||||
if len(self.correlation_index[value_item]['nodes']) > 1:
|
||||
self._create_correlation_relationships(value_item, self.correlation_index[value_item], result, discovery_time)
|
||||
correlations_found += 1
|
||||
|
||||
# Log correlation results
|
||||
if correlations_found > 0:
|
||||
self.logger.logger.info(f"Found {correlations_found} correlations for node {node_id}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.logger.error(f"Error finding correlations for {node_id}: {e}")
|
||||
|
||||
return result
|
||||
|
||||
def _should_exclude_attribute(self, attr_name: str, attr_value: Any) -> bool:
|
||||
"""
|
||||
Enhanced logic to determine if an attribute should be excluded from correlation.
|
||||
"""
|
||||
# Check against excluded keys (exact match or substring)
|
||||
if any(excluded_key in attr_name or attr_name == excluded_key for excluded_key in self.EXCLUDED_KEYS):
|
||||
return True
|
||||
|
||||
# Value type filtering
|
||||
if not isinstance(attr_value, (str, int, float, bool)) or attr_value is None:
|
||||
return True
|
||||
|
||||
# Boolean values are not useful for correlation
|
||||
if isinstance(attr_value, bool):
|
||||
return True
|
||||
|
||||
# String value filtering
|
||||
if isinstance(attr_value, str):
|
||||
# Date/timestamp strings
|
||||
if self.date_pattern.match(attr_value):
|
||||
return True
|
||||
|
||||
# Common non-useful values
|
||||
if attr_value.lower() in ['unknown', 'none', 'null', 'n/a', 'true', 'false', '0', '1']:
|
||||
return True
|
||||
|
||||
# Very long strings that are likely unique (> 100 chars)
|
||||
if len(attr_value) > 100:
|
||||
return True
|
||||
|
||||
# Numeric value filtering
|
||||
if isinstance(attr_value, (int, float)):
|
||||
# Very common values
|
||||
if attr_value in [0, 1]:
|
||||
return True
|
||||
|
||||
# Very large numbers (likely timestamps or unique IDs)
|
||||
if abs(attr_value) > 1000000:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _create_correlation_relationships(self, value: Any, correlation_data: Dict[str, Any],
|
||||
result: ProviderResult, discovery_time: datetime):
|
||||
"""
|
||||
Create correlation relationships with enhanced deduplication and validation.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
correlation_node_id = f"corr_{hash(str(value)) & 0x7FFFFFFF}"
|
||||
nodes = correlation_data['nodes']
|
||||
sources = correlation_data['sources']
|
||||
|
||||
# Only create correlations if we have meaningful nodes (more than 1)
|
||||
if len(nodes) < 2:
|
||||
return
|
||||
|
||||
# Limit correlation size to prevent overly large correlation objects
|
||||
MAX_CORRELATION_SIZE = 50
|
||||
if len(nodes) > MAX_CORRELATION_SIZE:
|
||||
# Sample the nodes to keep correlation manageable
|
||||
import random
|
||||
sampled_nodes = random.sample(list(nodes), MAX_CORRELATION_SIZE)
|
||||
nodes = set(sampled_nodes)
|
||||
# Filter sources to match sampled nodes
|
||||
sources = [s for s in sources if s['node_id'] in nodes]
|
||||
|
||||
# Add the correlation node as an attribute to the result
|
||||
result.add_attribute(
|
||||
target_node=correlation_node_id,
|
||||
name="correlation_value",
|
||||
value=value,
|
||||
attr_type=str(type(value).__name__),
|
||||
provider=self.name,
|
||||
metadata={
|
||||
'correlated_nodes': list(nodes),
|
||||
'sources': sources,
|
||||
'correlation_size': len(nodes),
|
||||
'value_type': type(value).__name__
|
||||
}
|
||||
)
|
||||
|
||||
# Create relationships with source validation and enhanced timestamps
|
||||
created_relationships = set()
|
||||
|
||||
for source in sources:
|
||||
node_id = source['node_id']
|
||||
provider = source['provider']
|
||||
attribute = source['attribute']
|
||||
|
||||
# Skip if we've already created this relationship
|
||||
relationship_key = (node_id, correlation_node_id)
|
||||
if relationship_key in created_relationships:
|
||||
continue
|
||||
|
||||
relationship_label = f"corr_{provider}_{attribute}"
|
||||
|
||||
# Enhanced raw_data with discovery timestamp for time-based edge coloring
|
||||
raw_data = {
|
||||
'correlation_value': value,
|
||||
'original_attribute': attribute,
|
||||
'correlation_type': 'attribute_matching',
|
||||
'correlation_size': len(nodes),
|
||||
'discovery_timestamp': discovery_time.isoformat(),
|
||||
'relevance_timestamp': discovery_time.isoformat() # Correlation data is "fresh" when discovered
|
||||
}
|
||||
|
||||
# Add the relationship to the result
|
||||
result.add_relationship(
|
||||
source_node=node_id,
|
||||
target_node=correlation_node_id,
|
||||
relationship_type=relationship_label,
|
||||
provider=self.name,
|
||||
raw_data=raw_data
|
||||
)
|
||||
|
||||
created_relationships.add(relationship_key)
|
||||
@@ -1,9 +1,9 @@
|
||||
# dnsrecon/providers/crtsh_provider.py
|
||||
# DNScope/providers/crtsh_provider.py
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any, Set
|
||||
from typing import List, Dict, Any, Set, Optional
|
||||
from urllib.parse import quote
|
||||
from datetime import datetime, timezone
|
||||
import requests
|
||||
@@ -11,13 +11,14 @@ import requests
|
||||
from .base_provider import BaseProvider
|
||||
from core.provider_result import ProviderResult
|
||||
from utils.helpers import _is_valid_domain
|
||||
|
||||
from core.logger import get_forensic_logger
|
||||
|
||||
class CrtShProvider(BaseProvider):
|
||||
"""
|
||||
Provider for querying crt.sh certificate transparency database.
|
||||
FIXED: Now properly creates domain and CA nodes instead of large entities.
|
||||
FIXED: Improved caching logic and error handling to prevent infinite retry loops.
|
||||
Returns standardized ProviderResult objects with caching support.
|
||||
UPDATED: Enhanced with certificate timestamps for time-based edge coloring.
|
||||
"""
|
||||
|
||||
def __init__(self, name=None, session_config=None):
|
||||
@@ -31,7 +32,7 @@ class CrtShProvider(BaseProvider):
|
||||
self.base_url = "https://crt.sh/"
|
||||
self._stop_event = None
|
||||
|
||||
# Initialize cache directory (separate from BaseProvider's HTTP cache)
|
||||
# Initialize cache directory
|
||||
self.domain_cache_dir = Path('cache') / 'crtsh'
|
||||
self.domain_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -65,43 +66,73 @@ class CrtShProvider(BaseProvider):
|
||||
|
||||
def _get_cache_status(self, cache_file_path: Path) -> str:
|
||||
"""
|
||||
Check cache status for a domain.
|
||||
FIXED: More robust cache status checking with better error handling.
|
||||
Returns: 'not_found', 'fresh', or 'stale'
|
||||
"""
|
||||
if not cache_file_path.exists():
|
||||
return "not_found"
|
||||
|
||||
try:
|
||||
with open(cache_file_path, 'r') as f:
|
||||
cache_data = json.load(f)
|
||||
|
||||
last_query_str = cache_data.get("last_upstream_query")
|
||||
if not last_query_str:
|
||||
# Check if file is readable and not corrupted
|
||||
if cache_file_path.stat().st_size == 0:
|
||||
self.logger.logger.warning(f"Empty cache file: {cache_file_path}")
|
||||
return "stale"
|
||||
|
||||
last_query = datetime.fromisoformat(last_query_str.replace('Z', '+00:00'))
|
||||
hours_since_query = (datetime.now(timezone.utc) - last_query).total_seconds() / 3600
|
||||
with open(cache_file_path, 'r', encoding='utf-8') as f:
|
||||
cache_data = json.load(f)
|
||||
|
||||
# Validate cache structure
|
||||
if not isinstance(cache_data, dict):
|
||||
self.logger.logger.warning(f"Invalid cache structure: {cache_file_path}")
|
||||
return "stale"
|
||||
|
||||
last_query_str = cache_data.get("last_upstream_query")
|
||||
if not last_query_str or not isinstance(last_query_str, str):
|
||||
self.logger.logger.warning(f"Missing or invalid last_upstream_query: {cache_file_path}")
|
||||
return "stale"
|
||||
|
||||
try:
|
||||
# More robust datetime parsing
|
||||
if last_query_str.endswith('Z'):
|
||||
last_query = datetime.fromisoformat(last_query_str.replace('Z', '+00:00'))
|
||||
elif '+' in last_query_str or last_query_str.endswith('UTC'):
|
||||
# Handle various timezone formats
|
||||
clean_time = last_query_str.replace('UTC', '').strip()
|
||||
if '+' in clean_time:
|
||||
clean_time = clean_time.split('+')[0]
|
||||
last_query = datetime.fromisoformat(clean_time).replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
last_query = datetime.fromisoformat(last_query_str).replace(tzinfo=timezone.utc)
|
||||
|
||||
except (ValueError, AttributeError) as e:
|
||||
self.logger.logger.warning(f"Failed to parse timestamp in cache {cache_file_path}: {e}")
|
||||
return "stale"
|
||||
|
||||
hours_since_query = (datetime.now(timezone.utc) - last_query).total_seconds() / 3600
|
||||
cache_timeout = self.config.cache_timeout_hours
|
||||
|
||||
if hours_since_query < cache_timeout:
|
||||
return "fresh"
|
||||
else:
|
||||
return "stale"
|
||||
|
||||
except (json.JSONDecodeError, ValueError, KeyError) as e:
|
||||
self.logger.logger.warning(f"Invalid cache file format for {cache_file_path}: {e}")
|
||||
except (json.JSONDecodeError, OSError, PermissionError) as e:
|
||||
self.logger.logger.warning(f"Cache file error for {cache_file_path}: {e}")
|
||||
# FIXED: Try to remove corrupted cache file
|
||||
try:
|
||||
cache_file_path.unlink()
|
||||
self.logger.logger.info(f"Removed corrupted cache file: {cache_file_path}")
|
||||
except Exception:
|
||||
pass
|
||||
return "not_found"
|
||||
except Exception as e:
|
||||
self.logger.logger.error(f"Unexpected error checking cache status for {cache_file_path}: {e}")
|
||||
return "stale"
|
||||
|
||||
def query_domain(self, domain: str) -> ProviderResult:
|
||||
"""
|
||||
FIXED: Query crt.sh for certificates containing the domain.
|
||||
Now properly creates domain and CA nodes instead of large entities.
|
||||
|
||||
Args:
|
||||
domain: Domain to investigate
|
||||
|
||||
Returns:
|
||||
ProviderResult containing discovered relationships and attributes
|
||||
FIXED: Simplified and more robust domain querying with better error handling.
|
||||
UPDATED: Enhanced with certificate timestamps for time-based edge coloring.
|
||||
"""
|
||||
if not _is_valid_domain(domain):
|
||||
return ProviderResult()
|
||||
@@ -110,130 +141,158 @@ class CrtShProvider(BaseProvider):
|
||||
return ProviderResult()
|
||||
|
||||
cache_file = self._get_cache_file_path(domain)
|
||||
cache_status = self._get_cache_status(cache_file)
|
||||
|
||||
result = ProviderResult()
|
||||
|
||||
try:
|
||||
if cache_status == "fresh":
|
||||
result = self._load_from_cache(cache_file)
|
||||
self.logger.logger.info(f"Using fresh cached crt.sh data for {domain}")
|
||||
cache_status = self._get_cache_status(cache_file)
|
||||
|
||||
else: # "stale" or "not_found"
|
||||
# Query the API for the latest certificates
|
||||
if cache_status == "fresh":
|
||||
# Load from cache
|
||||
result = self._load_from_cache(cache_file)
|
||||
if result and (result.relationships or result.attributes):
|
||||
self.logger.logger.debug(f"Using fresh cached crt.sh data for {domain}")
|
||||
return result
|
||||
else:
|
||||
# Cache exists but is empty, treat as stale
|
||||
cache_status = "stale"
|
||||
|
||||
# Need to query API (either no cache, stale cache, or empty cache)
|
||||
self.logger.logger.debug(f"Querying crt.sh API for {domain} (cache status: {cache_status})")
|
||||
new_raw_certs = self._query_crtsh_api(domain)
|
||||
|
||||
if self._stop_event and self._stop_event.is_set():
|
||||
return ProviderResult()
|
||||
|
||||
# Combine with old data if cache is stale
|
||||
if cache_status == "stale":
|
||||
old_raw_certs = self._load_raw_data_from_cache(cache_file)
|
||||
combined_certs = old_raw_certs + new_raw_certs
|
||||
|
||||
# Deduplicate the combined list
|
||||
seen_ids = set()
|
||||
unique_certs = []
|
||||
for cert in combined_certs:
|
||||
cert_id = cert.get('id')
|
||||
if cert_id not in seen_ids:
|
||||
unique_certs.append(cert)
|
||||
seen_ids.add(cert_id)
|
||||
|
||||
raw_certificates_to_process = unique_certs
|
||||
self.logger.logger.info(f"Refreshed and merged cache for {domain}. Total unique certs: {len(raw_certificates_to_process)}")
|
||||
else: # "not_found"
|
||||
# FIXED: Simplified processing - just process the new data
|
||||
# Don't try to merge with stale cache as it can cause corruption
|
||||
raw_certificates_to_process = new_raw_certs
|
||||
|
||||
# FIXED: Process certificates to create proper domain and CA nodes
|
||||
result = self._process_certificates_to_result_fixed(domain, raw_certificates_to_process)
|
||||
self.logger.logger.info(f"Created fresh result for {domain} ({result.get_relationship_count()} relationships)")
|
||||
|
||||
# Save the new result and the raw data to the cache
|
||||
self._save_result_to_cache(cache_file, result, raw_certificates_to_process, domain)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
self.logger.logger.error(f"API query failed for {domain}: {e}")
|
||||
if cache_status != "not_found":
|
||||
result = self._load_from_cache(cache_file)
|
||||
self.logger.logger.warning(f"Using stale cache for {domain} due to API failure.")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Refreshed stale cache for {domain} with {len(raw_certificates_to_process)} certs")
|
||||
else:
|
||||
raise e # Re-raise if there's no cache to fall back on
|
||||
self.logger.logger.info(f"Created fresh cache for {domain} with {len(raw_certificates_to_process)} certs")
|
||||
|
||||
result = self._process_certificates_to_result_fixed(domain, raw_certificates_to_process)
|
||||
|
||||
# Save the result to cache
|
||||
self._save_result_to_cache(cache_file, result, raw_certificates_to_process, domain)
|
||||
|
||||
return result
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
# FIXED: Don't re-raise network errors after long idle periods
|
||||
# Instead return empty result and log the issue
|
||||
self.logger.logger.warning(f"Network error querying crt.sh for {domain}: {e}")
|
||||
|
||||
# Try to use stale cache if available
|
||||
if cache_status == "stale":
|
||||
try:
|
||||
stale_result = self._load_from_cache(cache_file)
|
||||
if stale_result and (stale_result.relationships or stale_result.attributes):
|
||||
self.logger.logger.info(f"Using stale cache for {domain} due to network error")
|
||||
return stale_result
|
||||
except Exception as cache_error:
|
||||
self.logger.logger.warning(f"Failed to load stale cache for {domain}: {cache_error}")
|
||||
|
||||
# Return empty result instead of raising - this prevents infinite retries
|
||||
return ProviderResult()
|
||||
|
||||
except Exception as e:
|
||||
# FIXED: Handle any other exceptions gracefully
|
||||
self.logger.logger.error(f"Unexpected error querying crt.sh for {domain}: {e}")
|
||||
|
||||
# Try stale cache as fallback
|
||||
try:
|
||||
if cache_file.exists():
|
||||
fallback_result = self._load_from_cache(cache_file)
|
||||
if fallback_result and (fallback_result.relationships or fallback_result.attributes):
|
||||
self.logger.logger.info(f"Using cached data for {domain} due to processing error")
|
||||
return fallback_result
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Return empty result to prevent retries
|
||||
return ProviderResult()
|
||||
|
||||
def query_ip(self, ip: str) -> ProviderResult:
|
||||
"""
|
||||
Query crt.sh for certificates containing the IP address.
|
||||
Note: crt.sh doesn't typically index by IP, so this returns empty results.
|
||||
|
||||
Args:
|
||||
ip: IP address to investigate
|
||||
|
||||
Returns:
|
||||
Empty ProviderResult (crt.sh doesn't support IP-based certificate queries effectively)
|
||||
crt.sh does not support IP-based certificate queries effectively via its API.
|
||||
"""
|
||||
return ProviderResult()
|
||||
|
||||
def _load_from_cache(self, cache_file_path: Path) -> ProviderResult:
|
||||
"""Load processed crt.sh data from a cache file."""
|
||||
"""FIXED: More robust cache loading with better validation."""
|
||||
try:
|
||||
with open(cache_file_path, 'r') as f:
|
||||
if not cache_file_path.exists() or cache_file_path.stat().st_size == 0:
|
||||
return ProviderResult()
|
||||
|
||||
with open(cache_file_path, 'r', encoding='utf-8') as f:
|
||||
cache_content = json.load(f)
|
||||
|
||||
if not isinstance(cache_content, dict):
|
||||
self.logger.logger.warning(f"Invalid cache format in {cache_file_path}")
|
||||
return ProviderResult()
|
||||
|
||||
result = ProviderResult()
|
||||
|
||||
# Reconstruct relationships
|
||||
for rel_data in cache_content.get("relationships", []):
|
||||
# Reconstruct relationships with validation
|
||||
relationships = cache_content.get("relationships", [])
|
||||
if isinstance(relationships, list):
|
||||
for rel_data in relationships:
|
||||
if not isinstance(rel_data, dict):
|
||||
continue
|
||||
try:
|
||||
result.add_relationship(
|
||||
source_node=rel_data["source_node"],
|
||||
target_node=rel_data["target_node"],
|
||||
relationship_type=rel_data["relationship_type"],
|
||||
provider=rel_data["provider"],
|
||||
confidence=rel_data["confidence"],
|
||||
source_node=rel_data.get("source_node", ""),
|
||||
target_node=rel_data.get("target_node", ""),
|
||||
relationship_type=rel_data.get("relationship_type", ""),
|
||||
provider=rel_data.get("provider", self.name),
|
||||
raw_data=rel_data.get("raw_data", {})
|
||||
)
|
||||
except (ValueError, TypeError) as e:
|
||||
self.logger.logger.warning(f"Skipping invalid relationship in cache: {e}")
|
||||
continue
|
||||
|
||||
# Reconstruct attributes
|
||||
for attr_data in cache_content.get("attributes", []):
|
||||
# Reconstruct attributes with validation
|
||||
attributes = cache_content.get("attributes", [])
|
||||
if isinstance(attributes, list):
|
||||
for attr_data in attributes:
|
||||
if not isinstance(attr_data, dict):
|
||||
continue
|
||||
try:
|
||||
result.add_attribute(
|
||||
target_node=attr_data["target_node"],
|
||||
name=attr_data["name"],
|
||||
value=attr_data["value"],
|
||||
attr_type=attr_data["type"],
|
||||
provider=attr_data["provider"],
|
||||
confidence=attr_data["confidence"],
|
||||
target_node=attr_data.get("target_node", ""),
|
||||
name=attr_data.get("name", ""),
|
||||
value=attr_data.get("value"),
|
||||
attr_type=attr_data.get("type", "unknown"),
|
||||
provider=attr_data.get("provider", self.name),
|
||||
metadata=attr_data.get("metadata", {})
|
||||
)
|
||||
except (ValueError, TypeError) as e:
|
||||
self.logger.logger.warning(f"Skipping invalid attribute in cache: {e}")
|
||||
continue
|
||||
|
||||
return result
|
||||
|
||||
except (json.JSONDecodeError, FileNotFoundError, KeyError) as e:
|
||||
self.logger.logger.error(f"Failed to load cached certificates from {cache_file_path}: {e}")
|
||||
except (json.JSONDecodeError, OSError, PermissionError) as e:
|
||||
self.logger.logger.warning(f"Failed to load cache from {cache_file_path}: {e}")
|
||||
return ProviderResult()
|
||||
except Exception as e:
|
||||
self.logger.logger.error(f"Unexpected error loading cache from {cache_file_path}: {e}")
|
||||
return ProviderResult()
|
||||
|
||||
def _load_raw_data_from_cache(self, cache_file_path: Path) -> List[Dict[str, Any]]:
|
||||
"""Load only the raw certificate data from a cache file."""
|
||||
try:
|
||||
with open(cache_file_path, 'r') as f:
|
||||
cache_content = json.load(f)
|
||||
return cache_content.get("raw_certificates", [])
|
||||
except (json.JSONDecodeError, FileNotFoundError):
|
||||
return []
|
||||
|
||||
def _save_result_to_cache(self, cache_file_path: Path, result: ProviderResult, raw_certificates: List[Dict[str, Any]], domain: str) -> None:
|
||||
"""Save processed crt.sh result and raw data to a cache file."""
|
||||
"""FIXED: More robust cache saving with atomic writes."""
|
||||
try:
|
||||
cache_data = {
|
||||
"domain": domain,
|
||||
"last_upstream_query": datetime.now(timezone.utc).isoformat(),
|
||||
"raw_certificates": raw_certificates, # Store the raw data for deduplication
|
||||
"raw_certificates": raw_certificates,
|
||||
"relationships": [
|
||||
{
|
||||
"source_node": rel.source_node,
|
||||
"target_node": rel.target_node,
|
||||
"relationship_type": rel.relationship_type,
|
||||
"confidence": rel.confidence,
|
||||
"provider": rel.provider,
|
||||
"raw_data": rel.raw_data
|
||||
} for rel in result.relationships
|
||||
@@ -245,40 +304,73 @@ class CrtShProvider(BaseProvider):
|
||||
"value": attr.value,
|
||||
"type": attr.type,
|
||||
"provider": attr.provider,
|
||||
"confidence": attr.confidence,
|
||||
"metadata": attr.metadata
|
||||
} for attr in result.attributes
|
||||
]
|
||||
}
|
||||
|
||||
cache_file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(cache_file_path, 'w') as f:
|
||||
json.dump(cache_data, f, separators=(',', ':'), default=str)
|
||||
|
||||
# FIXED: Atomic write using temporary file
|
||||
temp_file = cache_file_path.with_suffix('.tmp')
|
||||
try:
|
||||
with open(temp_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(cache_data, f, separators=(',', ':'), default=str, ensure_ascii=False)
|
||||
|
||||
# Atomic rename
|
||||
temp_file.replace(cache_file_path)
|
||||
self.logger.logger.debug(f"Saved cache for {domain} ({len(result.relationships)} relationships)")
|
||||
|
||||
except Exception as e:
|
||||
# Clean up temp file on error
|
||||
if temp_file.exists():
|
||||
try:
|
||||
temp_file.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise e
|
||||
|
||||
except Exception as e:
|
||||
self.logger.logger.warning(f"Failed to save cache file for {domain}: {e}")
|
||||
|
||||
def _query_crtsh_api(self, domain: str) -> List[Dict[str, Any]]:
|
||||
"""Query crt.sh API for raw certificate data."""
|
||||
"""FIXED: More robust API querying with better error handling."""
|
||||
url = f"{self.base_url}?q={quote(domain)}&output=json"
|
||||
response = self.make_request(url, target_indicator=domain)
|
||||
|
||||
if not response or response.status_code != 200:
|
||||
raise requests.exceptions.RequestException(f"crt.sh API returned status {response.status_code if response else 'None'}")
|
||||
|
||||
try:
|
||||
response = self.make_request(url, target_indicator=domain)
|
||||
|
||||
if not response:
|
||||
self.logger.logger.warning(f"No response from crt.sh for {domain}")
|
||||
return []
|
||||
|
||||
if response.status_code != 200:
|
||||
self.logger.logger.warning(f"crt.sh returned status {response.status_code} for {domain}")
|
||||
return []
|
||||
|
||||
# FIXED: Better JSON parsing with error handling
|
||||
try:
|
||||
certificates = response.json()
|
||||
except json.JSONDecodeError:
|
||||
self.logger.logger.error(f"crt.sh returned invalid JSON for {domain}")
|
||||
except json.JSONDecodeError as e:
|
||||
self.logger.logger.error(f"crt.sh returned invalid JSON for {domain}: {e}")
|
||||
return []
|
||||
|
||||
if not certificates:
|
||||
if not certificates or not isinstance(certificates, list):
|
||||
self.logger.logger.debug(f"crt.sh returned no certificates for {domain}")
|
||||
return []
|
||||
|
||||
self.logger.logger.debug(f"crt.sh returned {len(certificates)} certificates for {domain}")
|
||||
return certificates
|
||||
|
||||
except Exception as e:
|
||||
self.logger.logger.error(f"Error querying crt.sh API for {domain}: {e}")
|
||||
raise e
|
||||
|
||||
def _process_certificates_to_result_fixed(self, query_domain: str, certificates: List[Dict[str, Any]]) -> ProviderResult:
|
||||
"""
|
||||
FIXED: Process certificates to create proper domain and CA nodes.
|
||||
Now creates individual domain nodes instead of large entities.
|
||||
Process certificates to create proper domain and CA nodes.
|
||||
FIXED: Better error handling and progress tracking.
|
||||
UPDATED: Enhanced with certificate timestamps for time-based edge coloring.
|
||||
"""
|
||||
result = ProviderResult()
|
||||
|
||||
@@ -286,29 +378,63 @@ class CrtShProvider(BaseProvider):
|
||||
self.logger.logger.info(f"CrtSh processing cancelled before processing for domain: {query_domain}")
|
||||
return result
|
||||
|
||||
if not certificates:
|
||||
self.logger.logger.debug(f"No certificates to process for {query_domain}")
|
||||
return result
|
||||
|
||||
# Check for incomplete data warning
|
||||
incompleteness_warning = self._check_for_incomplete_data(query_domain, certificates)
|
||||
if incompleteness_warning:
|
||||
result.add_attribute(
|
||||
target_node=query_domain,
|
||||
name="crtsh_data_warning",
|
||||
value=incompleteness_warning,
|
||||
attr_type='metadata',
|
||||
provider=self.name
|
||||
)
|
||||
|
||||
all_discovered_domains = set()
|
||||
processed_issuers = set()
|
||||
processed_certs = 0
|
||||
|
||||
for i, cert_data in enumerate(certificates):
|
||||
if i % 10 == 0 and self._stop_event and self._stop_event.is_set():
|
||||
self.logger.logger.info(f"CrtSh processing cancelled at certificate {i} for domain: {query_domain}")
|
||||
# FIXED: More frequent stop checks and progress logging
|
||||
if i % 5 == 0:
|
||||
if self._stop_event and self._stop_event.is_set():
|
||||
self.logger.logger.info(f"CrtSh processing cancelled at certificate {i}/{len(certificates)} for domain: {query_domain}")
|
||||
break
|
||||
|
||||
if i > 0 and i % 100 == 0:
|
||||
self.logger.logger.debug(f"Processed {i}/{len(certificates)} certificates for {query_domain}")
|
||||
|
||||
try:
|
||||
# Extract all domains from this certificate
|
||||
cert_domains = self._extract_domains_from_certificate(cert_data)
|
||||
if cert_domains:
|
||||
all_discovered_domains.update(cert_domains)
|
||||
|
||||
# FIXED: Create CA nodes for certificate issuers (not as domain metadata)
|
||||
# Create CA nodes for certificate issuers with timestamp
|
||||
issuer_name = self._parse_issuer_organization(cert_data.get('issuer_name', ''))
|
||||
if issuer_name and issuer_name not in processed_issuers:
|
||||
# Create relationship from query domain to CA
|
||||
# Enhanced raw_data with certificate timestamp for time-based edge coloring
|
||||
issuer_raw_data = {'issuer_dn': cert_data.get('issuer_name', '')}
|
||||
|
||||
# Add certificate issue date (not_before) as relevance timestamp
|
||||
not_before = cert_data.get('not_before')
|
||||
if not_before:
|
||||
try:
|
||||
not_before_date = self._parse_certificate_date(not_before)
|
||||
issuer_raw_data['cert_not_before'] = not_before_date.isoformat()
|
||||
issuer_raw_data['relevance_timestamp'] = not_before_date.isoformat() # Standardized field
|
||||
except Exception as e:
|
||||
self.logger.logger.debug(f"Failed to parse not_before date for issuer: {e}")
|
||||
|
||||
result.add_relationship(
|
||||
source_node=query_domain,
|
||||
target_node=issuer_name,
|
||||
relationship_type='crtsh_cert_issuer',
|
||||
provider=self.name,
|
||||
confidence=0.95,
|
||||
raw_data={'issuer_dn': cert_data.get('issuer_name', '')}
|
||||
raw_data=issuer_raw_data
|
||||
)
|
||||
processed_issuers.add(issuer_name)
|
||||
|
||||
@@ -318,7 +444,6 @@ class CrtShProvider(BaseProvider):
|
||||
if not _is_valid_domain(cert_domain):
|
||||
continue
|
||||
|
||||
# Add certificate attributes to the domain
|
||||
for key, value in cert_metadata.items():
|
||||
if value is not None:
|
||||
result.add_attribute(
|
||||
@@ -327,16 +452,22 @@ class CrtShProvider(BaseProvider):
|
||||
value=value,
|
||||
attr_type='certificate_data',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
metadata={'certificate_id': cert_data.get('id')}
|
||||
)
|
||||
|
||||
processed_certs += 1
|
||||
|
||||
except Exception as e:
|
||||
self.logger.logger.warning(f"Error processing certificate {i} for {query_domain}: {e}")
|
||||
continue
|
||||
|
||||
# Check for stop event before creating final relationships
|
||||
if self._stop_event and self._stop_event.is_set():
|
||||
self.logger.logger.info(f"CrtSh query cancelled before relationship creation for domain: {query_domain}")
|
||||
return result
|
||||
|
||||
# FIXED: Create selective relationships to avoid large entities
|
||||
# Only create relationships to domains that are closely related
|
||||
# Create selective relationships to avoid large entities with enhanced timestamps
|
||||
relationships_created = 0
|
||||
for discovered_domain in all_discovered_domains:
|
||||
if discovered_domain == query_domain:
|
||||
continue
|
||||
@@ -344,48 +475,80 @@ class CrtShProvider(BaseProvider):
|
||||
if not _is_valid_domain(discovered_domain):
|
||||
continue
|
||||
|
||||
# FIXED: Only create relationships for domains that share a meaningful connection
|
||||
# This prevents creating too many relationships that trigger large entity creation
|
||||
if self._should_create_relationship(query_domain, discovered_domain):
|
||||
confidence = self._calculate_domain_relationship_confidence(
|
||||
query_domain, discovered_domain, [], all_discovered_domains
|
||||
# Enhanced raw_data with certificate timestamp for domain relationships
|
||||
domain_raw_data = {'relationship_type': 'certificate_discovery'}
|
||||
|
||||
# Find the most recent certificate for this domain pair to use as timestamp
|
||||
most_recent_cert = self._find_most_recent_cert_for_domains(
|
||||
certificates, query_domain, discovered_domain
|
||||
)
|
||||
if most_recent_cert:
|
||||
not_before = most_recent_cert.get('not_before')
|
||||
if not_before:
|
||||
try:
|
||||
not_before_date = self._parse_certificate_date(not_before)
|
||||
domain_raw_data['cert_not_before'] = not_before_date.isoformat()
|
||||
domain_raw_data['relevance_timestamp'] = not_before_date.isoformat()
|
||||
except Exception as e:
|
||||
self.logger.logger.debug(f"Failed to parse not_before date for domain relationship: {e}")
|
||||
|
||||
result.add_relationship(
|
||||
source_node=query_domain,
|
||||
target_node=discovered_domain,
|
||||
relationship_type='crtsh_san_certificate',
|
||||
provider=self.name,
|
||||
confidence=confidence,
|
||||
raw_data={'relationship_type': 'certificate_discovery'}
|
||||
raw_data=domain_raw_data
|
||||
)
|
||||
|
||||
self.log_relationship_discovery(
|
||||
source_node=query_domain,
|
||||
target_node=discovered_domain,
|
||||
relationship_type='crtsh_san_certificate',
|
||||
confidence_score=confidence,
|
||||
raw_data={'relationship_type': 'certificate_discovery'},
|
||||
raw_data=domain_raw_data,
|
||||
discovery_method="certificate_transparency_analysis"
|
||||
)
|
||||
relationships_created += 1
|
||||
|
||||
self.logger.logger.info(f"CrtSh processing completed for {query_domain}: {len(all_discovered_domains)} domains, {result.get_relationship_count()} relationships")
|
||||
self.logger.logger.info(f"CrtSh processing completed for {query_domain}: processed {processed_certs}/{len(certificates)} certificates, {len(all_discovered_domains)} domains, {relationships_created} relationships")
|
||||
return result
|
||||
|
||||
def _find_most_recent_cert_for_domains(self, certificates: List[Dict[str, Any]],
|
||||
domain1: str, domain2: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Find the most recent certificate that contains both domains.
|
||||
Used for determining the relevance timestamp for domain relationships.
|
||||
"""
|
||||
most_recent_cert = None
|
||||
most_recent_date = None
|
||||
|
||||
for cert in certificates:
|
||||
# Check if this certificate contains both domains
|
||||
cert_domains = self._extract_domains_from_certificate(cert)
|
||||
if domain1 in cert_domains and domain2 in cert_domains:
|
||||
not_before = cert.get('not_before')
|
||||
if not_before:
|
||||
try:
|
||||
cert_date = self._parse_certificate_date(not_before)
|
||||
if most_recent_date is None or cert_date > most_recent_date:
|
||||
most_recent_date = cert_date
|
||||
most_recent_cert = cert
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
return most_recent_cert
|
||||
|
||||
# [Rest of the methods remain the same as in the original file]
|
||||
def _should_create_relationship(self, source_domain: str, target_domain: str) -> bool:
|
||||
"""
|
||||
FIXED: Determine if a relationship should be created between two domains.
|
||||
This helps avoid creating too many relationships that trigger large entity creation.
|
||||
Determine if a relationship should be created between two domains.
|
||||
"""
|
||||
# Always create relationships for subdomains
|
||||
if target_domain.endswith(f'.{source_domain}') or source_domain.endswith(f'.{target_domain}'):
|
||||
return True
|
||||
|
||||
# Create relationships for domains that share a common parent (up to 2 levels)
|
||||
source_parts = source_domain.split('.')
|
||||
target_parts = target_domain.split('.')
|
||||
|
||||
# Check if they share the same root domain (last 2 parts)
|
||||
if len(source_parts) >= 2 and len(target_parts) >= 2:
|
||||
source_root = '.'.join(source_parts[-2:])
|
||||
target_root = '.'.join(target_parts[-2:])
|
||||
@@ -419,7 +582,6 @@ class CrtShProvider(BaseProvider):
|
||||
metadata['is_currently_valid'] = self._is_cert_valid(cert_data)
|
||||
metadata['expires_soon'] = (not_after - datetime.now(timezone.utc)).days <= 30
|
||||
|
||||
# Keep raw date format or convert to standard format
|
||||
metadata['not_before'] = not_before.isoformat()
|
||||
metadata['not_after'] = not_after.isoformat()
|
||||
|
||||
@@ -457,6 +619,8 @@ class CrtShProvider(BaseProvider):
|
||||
raise ValueError("Empty date string")
|
||||
|
||||
try:
|
||||
if isinstance(date_string, datetime):
|
||||
return date_string.replace(tzinfo=timezone.utc)
|
||||
if date_string.endswith('Z'):
|
||||
return datetime.fromisoformat(date_string[:-1]).replace(tzinfo=timezone.utc)
|
||||
elif '+' in date_string or date_string.endswith('UTC'):
|
||||
@@ -499,14 +663,12 @@ class CrtShProvider(BaseProvider):
|
||||
"""Extract all domains from certificate data."""
|
||||
domains = set()
|
||||
|
||||
# Extract from common name
|
||||
common_name = cert_data.get('common_name', '')
|
||||
if common_name:
|
||||
cleaned_cn = self._clean_domain_name(common_name)
|
||||
if cleaned_cn:
|
||||
domains.update(cleaned_cn)
|
||||
|
||||
# Extract from name_value field (contains SANs)
|
||||
name_value = cert_data.get('name_value', '')
|
||||
if name_value:
|
||||
for line in name_value.split('\n'):
|
||||
@@ -547,26 +709,6 @@ class CrtShProvider(BaseProvider):
|
||||
|
||||
return [d for d in final_domains if _is_valid_domain(d)]
|
||||
|
||||
def _calculate_domain_relationship_confidence(self, domain1: str, domain2: str,
|
||||
shared_certificates: List[Dict[str, Any]],
|
||||
all_discovered_domains: Set[str]) -> float:
|
||||
"""Calculate confidence score for domain relationship based on various factors."""
|
||||
base_confidence = 0.9
|
||||
|
||||
# Adjust confidence based on domain relationship context
|
||||
relationship_context = self._determine_relationship_context(domain2, domain1)
|
||||
|
||||
if relationship_context == 'exact_match':
|
||||
context_bonus = 0.0
|
||||
elif relationship_context == 'subdomain':
|
||||
context_bonus = 0.1
|
||||
elif relationship_context == 'parent_domain':
|
||||
context_bonus = 0.05
|
||||
else:
|
||||
context_bonus = 0.0
|
||||
|
||||
final_confidence = base_confidence + context_bonus
|
||||
return max(0.1, min(1.0, final_confidence))
|
||||
|
||||
def _determine_relationship_context(self, cert_domain: str, query_domain: str) -> str:
|
||||
"""Determine the context of the relationship between certificate domain and query domain."""
|
||||
@@ -578,3 +720,27 @@ class CrtShProvider(BaseProvider):
|
||||
return 'parent_domain'
|
||||
else:
|
||||
return 'related_domain'
|
||||
|
||||
def _check_for_incomplete_data(self, domain: str, certificates: List[Dict[str, Any]]) -> Optional[str]:
|
||||
"""
|
||||
Analyzes the certificate list to heuristically detect if the data from crt.sh is incomplete.
|
||||
"""
|
||||
cert_count = len(certificates)
|
||||
|
||||
if cert_count >= 10000:
|
||||
return f"Result likely truncated; received {cert_count} certificates, which may be the maximum limit."
|
||||
|
||||
if cert_count > 1000:
|
||||
latest_expiry = None
|
||||
for cert in certificates:
|
||||
try:
|
||||
not_after = self._parse_certificate_date(cert.get('not_after'))
|
||||
if latest_expiry is None or not_after > latest_expiry:
|
||||
latest_expiry = not_after
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
|
||||
if latest_expiry and (datetime.now(timezone.utc) - latest_expiry).days > 365:
|
||||
return f"Incomplete data suspected: The latest certificate expired more than a year ago ({latest_expiry.strftime('%Y-%m-%d')})."
|
||||
|
||||
return None
|
||||
@@ -1,7 +1,8 @@
|
||||
# dnsrecon/providers/dns_provider.py
|
||||
# DNScope/providers/dns_provider.py
|
||||
|
||||
from dns import resolver, reversename
|
||||
from typing import Dict
|
||||
from datetime import datetime, timezone
|
||||
from .base_provider import BaseProvider
|
||||
from core.provider_result import ProviderResult
|
||||
from utils.helpers import _is_valid_ip, _is_valid_domain, get_ip_version
|
||||
@@ -11,6 +12,7 @@ class DNSProvider(BaseProvider):
|
||||
"""
|
||||
Provider for standard DNS resolution and reverse DNS lookups.
|
||||
Now returns standardized ProviderResult objects with IPv4 and IPv6 support.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
|
||||
def __init__(self, name=None, session_config=None):
|
||||
@@ -51,6 +53,7 @@ class DNSProvider(BaseProvider):
|
||||
"""
|
||||
Query DNS records for the domain to discover relationships and attributes.
|
||||
FIXED: Now creates separate attributes for each DNS record type.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
|
||||
Args:
|
||||
domain: Domain to investigate
|
||||
@@ -62,11 +65,12 @@ class DNSProvider(BaseProvider):
|
||||
return ProviderResult()
|
||||
|
||||
result = ProviderResult()
|
||||
discovery_time = datetime.now(timezone.utc)
|
||||
|
||||
# Query all record types - each gets its own attribute
|
||||
for record_type in ['A', 'AAAA', 'CNAME', 'MX', 'NS', 'SOA', 'TXT', 'SRV', 'CAA']:
|
||||
try:
|
||||
self._query_record(domain, record_type, result)
|
||||
self._query_record(domain, record_type, result, discovery_time)
|
||||
#except resolver.NoAnswer:
|
||||
# This is not an error, just a confirmation that the record doesn't exist.
|
||||
#self.logger.logger.debug(f"No {record_type} record found for {domain}")
|
||||
@@ -79,6 +83,7 @@ class DNSProvider(BaseProvider):
|
||||
def query_ip(self, ip: str) -> ProviderResult:
|
||||
"""
|
||||
Query reverse DNS for the IP address (supports both IPv4 and IPv6).
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
|
||||
Args:
|
||||
ip: IP address to investigate (IPv4 or IPv6)
|
||||
@@ -91,6 +96,7 @@ class DNSProvider(BaseProvider):
|
||||
|
||||
result = ProviderResult()
|
||||
ip_version = get_ip_version(ip)
|
||||
discovery_time = datetime.now(timezone.utc)
|
||||
|
||||
try:
|
||||
# Perform reverse DNS lookup (works for both IPv4 and IPv6)
|
||||
@@ -112,20 +118,24 @@ class DNSProvider(BaseProvider):
|
||||
relationship_type = 'dns_a_record'
|
||||
record_prefix = 'A'
|
||||
|
||||
# Enhanced raw_data with discovery timestamp for time-based edge coloring
|
||||
raw_data = {
|
||||
'query_type': 'PTR',
|
||||
'ip_address': ip,
|
||||
'ip_version': ip_version,
|
||||
'hostname': hostname,
|
||||
'ttl': response.ttl,
|
||||
'discovery_timestamp': discovery_time.isoformat(),
|
||||
'relevance_timestamp': discovery_time.isoformat() # DNS data is "fresh" when discovered
|
||||
}
|
||||
|
||||
# Add the relationship
|
||||
result.add_relationship(
|
||||
source_node=ip,
|
||||
target_node=hostname,
|
||||
relationship_type='dns_ptr_record',
|
||||
provider=self.name,
|
||||
confidence=0.8,
|
||||
raw_data={
|
||||
'query_type': 'PTR',
|
||||
'ip_address': ip,
|
||||
'ip_version': ip_version,
|
||||
'hostname': hostname,
|
||||
'ttl': response.ttl
|
||||
}
|
||||
raw_data=raw_data
|
||||
)
|
||||
|
||||
# Add to PTR records list
|
||||
@@ -136,14 +146,7 @@ class DNSProvider(BaseProvider):
|
||||
source_node=ip,
|
||||
target_node=hostname,
|
||||
relationship_type='dns_ptr_record',
|
||||
confidence_score=0.8,
|
||||
raw_data={
|
||||
'query_type': 'PTR',
|
||||
'ip_address': ip,
|
||||
'ip_version': ip_version,
|
||||
'hostname': hostname,
|
||||
'ttl': response.ttl
|
||||
},
|
||||
raw_data=raw_data,
|
||||
discovery_method=f"reverse_dns_lookup_ipv{ip_version}"
|
||||
)
|
||||
|
||||
@@ -155,7 +158,6 @@ class DNSProvider(BaseProvider):
|
||||
value=ptr_records,
|
||||
attr_type='dns_record',
|
||||
provider=self.name,
|
||||
confidence=0.8,
|
||||
metadata={'ttl': response.ttl, 'ip_version': ip_version}
|
||||
)
|
||||
|
||||
@@ -170,10 +172,11 @@ class DNSProvider(BaseProvider):
|
||||
|
||||
return result
|
||||
|
||||
def _query_record(self, domain: str, record_type: str, result: ProviderResult) -> None:
|
||||
def _query_record(self, domain: str, record_type: str, result: ProviderResult, discovery_time: datetime) -> None:
|
||||
"""
|
||||
FIXED: Query DNS records with unique attribute names for each record type.
|
||||
Enhanced to better handle IPv6 AAAA records.
|
||||
UPDATED: Enhanced with discovery timestamps for time-based edge coloring.
|
||||
"""
|
||||
try:
|
||||
self.total_requests += 1
|
||||
@@ -217,18 +220,20 @@ class DNSProvider(BaseProvider):
|
||||
if record_type in ['A', 'AAAA'] and _is_valid_ip(target):
|
||||
ip_version = get_ip_version(target)
|
||||
|
||||
# Enhanced raw_data with discovery timestamp for time-based edge coloring
|
||||
raw_data = {
|
||||
'query_type': record_type,
|
||||
'domain': domain,
|
||||
'value': target,
|
||||
'ttl': response.ttl
|
||||
'ttl': response.ttl,
|
||||
'discovery_timestamp': discovery_time.isoformat(),
|
||||
'relevance_timestamp': discovery_time.isoformat() # DNS data is "fresh" when discovered
|
||||
}
|
||||
|
||||
if ip_version:
|
||||
raw_data['ip_version'] = ip_version
|
||||
|
||||
relationship_type = f"dns_{record_type.lower()}_record"
|
||||
confidence = 0.8
|
||||
|
||||
# Add relationship
|
||||
result.add_relationship(
|
||||
@@ -236,7 +241,6 @@ class DNSProvider(BaseProvider):
|
||||
target_node=target,
|
||||
relationship_type=relationship_type,
|
||||
provider=self.name,
|
||||
confidence=confidence,
|
||||
raw_data=raw_data
|
||||
)
|
||||
|
||||
@@ -252,7 +256,6 @@ class DNSProvider(BaseProvider):
|
||||
source_node=domain,
|
||||
target_node=target,
|
||||
relationship_type=relationship_type,
|
||||
confidence_score=confidence,
|
||||
raw_data=raw_data,
|
||||
discovery_method=discovery_method
|
||||
)
|
||||
@@ -276,7 +279,6 @@ class DNSProvider(BaseProvider):
|
||||
value=dns_records,
|
||||
attr_type='dns_record_list',
|
||||
provider=self.name,
|
||||
confidence=0.8,
|
||||
metadata=metadata
|
||||
)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# dnsrecon/providers/shodan_provider.py
|
||||
# DNScope/providers/shodan_provider.py
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -15,6 +15,7 @@ class ShodanProvider(BaseProvider):
|
||||
"""
|
||||
Provider for querying Shodan API for IP address information.
|
||||
Now returns standardized ProviderResult objects with caching support for IPv4 and IPv6.
|
||||
UPDATED: Enhanced with last_seen timestamp for time-based edge coloring.
|
||||
"""
|
||||
|
||||
def __init__(self, name=None, session_config=None):
|
||||
@@ -28,13 +29,52 @@ class ShodanProvider(BaseProvider):
|
||||
self.base_url = "https://api.shodan.io"
|
||||
self.api_key = self.config.get_api_key('shodan')
|
||||
|
||||
# FIXED: Don't fail initialization on connection issues - defer to actual usage
|
||||
self._connection_tested = False
|
||||
self._connection_works = False
|
||||
|
||||
# Initialize cache directory
|
||||
self.cache_dir = Path('cache') / 'shodan'
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _check_api_connection(self) -> bool:
|
||||
"""
|
||||
FIXED: Lazy connection checking - only test when actually needed.
|
||||
Don't block provider initialization on network issues.
|
||||
"""
|
||||
if self._connection_tested:
|
||||
return self._connection_works
|
||||
|
||||
if not self.api_key:
|
||||
self._connection_tested = True
|
||||
self._connection_works = False
|
||||
return False
|
||||
|
||||
try:
|
||||
print(f"Testing Shodan API connection with key: {self.api_key[:8]}...")
|
||||
response = self.session.get(f"{self.base_url}/api-info?key={self.api_key}", timeout=5)
|
||||
self._connection_works = response.status_code == 200
|
||||
print(f"Shodan API test result: {response.status_code} - {'Success' if self._connection_works else 'Failed'}")
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Shodan API connection test failed: {e}")
|
||||
self._connection_works = False
|
||||
finally:
|
||||
self._connection_tested = True
|
||||
|
||||
return self._connection_works
|
||||
|
||||
def is_available(self) -> bool:
|
||||
"""Check if Shodan provider is available (has valid API key in this session)."""
|
||||
return self.api_key is not None and len(self.api_key.strip()) > 0
|
||||
"""
|
||||
FIXED: Check if Shodan provider is available based on API key presence.
|
||||
Don't require successful connection test during initialization.
|
||||
"""
|
||||
has_api_key = self.api_key is not None and len(self.api_key.strip()) > 0
|
||||
|
||||
if not has_api_key:
|
||||
return False
|
||||
|
||||
# FIXED: Only test connection on first actual usage, not during initialization
|
||||
return True
|
||||
|
||||
def get_name(self) -> str:
|
||||
"""Return the provider name."""
|
||||
@@ -98,27 +138,31 @@ class ShodanProvider(BaseProvider):
|
||||
|
||||
def query_domain(self, domain: str) -> ProviderResult:
|
||||
"""
|
||||
Domain queries are no longer supported for the Shodan provider.
|
||||
|
||||
Args:
|
||||
domain: Domain to investigate
|
||||
|
||||
Returns:
|
||||
Empty ProviderResult
|
||||
Shodan does not support domain queries. This method returns an empty result.
|
||||
"""
|
||||
return ProviderResult()
|
||||
|
||||
def query_ip(self, ip: str) -> ProviderResult:
|
||||
"""
|
||||
Query Shodan for information about an IP address (IPv4 or IPv6), with caching of processed data.
|
||||
FIXED: Proper 404 handling to prevent unnecessary retries.
|
||||
UPDATED: Enhanced with last_seen timestamp extraction for time-based edge coloring.
|
||||
|
||||
Args:
|
||||
ip: IP address to investigate (IPv4 or IPv6)
|
||||
|
||||
Returns:
|
||||
ProviderResult containing discovered relationships and attributes
|
||||
|
||||
Raises:
|
||||
Exception: For temporary failures that should be retried (timeouts, 502/503 errors, connection issues)
|
||||
"""
|
||||
if not _is_valid_ip(ip) or not self.is_available():
|
||||
if not _is_valid_ip(ip):
|
||||
return ProviderResult()
|
||||
|
||||
# Test connection only when actually making requests
|
||||
if not self._check_api_connection():
|
||||
print(f"Shodan API not available for {ip} - API key: {'present' if self.api_key else 'missing'}")
|
||||
return ProviderResult()
|
||||
|
||||
# Normalize IP address for consistent processing
|
||||
@@ -129,54 +173,122 @@ class ShodanProvider(BaseProvider):
|
||||
cache_file = self._get_cache_file_path(normalized_ip)
|
||||
cache_status = self._get_cache_status(cache_file)
|
||||
|
||||
result = ProviderResult()
|
||||
|
||||
try:
|
||||
if cache_status == "fresh":
|
||||
result = self._load_from_cache(cache_file)
|
||||
self.logger.logger.info(f"Using cached Shodan data for {normalized_ip}")
|
||||
else: # "stale" or "not_found"
|
||||
self.logger.logger.debug(f"Using fresh cache for Shodan query: {normalized_ip}")
|
||||
return self._load_from_cache(cache_file)
|
||||
|
||||
# Need to query API
|
||||
self.logger.logger.debug(f"Querying Shodan API for: {normalized_ip}")
|
||||
url = f"{self.base_url}/shodan/host/{normalized_ip}"
|
||||
params = {'key': self.api_key}
|
||||
|
||||
try:
|
||||
response = self.make_request(url, method="GET", params=params, target_indicator=normalized_ip)
|
||||
|
||||
if response and response.status_code == 200:
|
||||
data = response.json()
|
||||
# Process the data into ProviderResult BEFORE caching
|
||||
result = self._process_shodan_data(normalized_ip, data)
|
||||
self._save_to_cache(cache_file, result, data) # Save both result and raw data
|
||||
elif response and response.status_code == 404:
|
||||
# Handle 404 "No information available" as successful empty result
|
||||
if not response:
|
||||
self.logger.logger.warning(f"Shodan API unreachable for {normalized_ip} - network failure")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to network failure")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
# FIXED: Treat network failures as "no information" rather than retryable errors
|
||||
self.logger.logger.info(f"No Shodan data available for {normalized_ip} due to network failure")
|
||||
result = ProviderResult() # Empty result
|
||||
network_failure_data = {'shodan_status': 'network_unreachable', 'error': 'API unreachable'}
|
||||
self._save_to_cache(cache_file, result, network_failure_data)
|
||||
return result
|
||||
|
||||
# FIXED: Handle different status codes more precisely
|
||||
if response.status_code == 200:
|
||||
self.logger.logger.debug(f"Shodan returned data for {normalized_ip}")
|
||||
try:
|
||||
error_data = response.json()
|
||||
if "No information available" in error_data.get('error', ''):
|
||||
# This is a successful query - Shodan just has no data
|
||||
self.logger.logger.debug(f"Shodan has no information for {normalized_ip}")
|
||||
data = response.json()
|
||||
result = self._process_shodan_data(normalized_ip, data)
|
||||
self._save_to_cache(cache_file, result, data)
|
||||
return result
|
||||
except json.JSONDecodeError as e:
|
||||
self.logger.logger.error(f"Invalid JSON response from Shodan for {normalized_ip}: {e}")
|
||||
if cache_status == "stale":
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
raise requests.exceptions.RequestException("Invalid JSON response from Shodan - should retry")
|
||||
|
||||
elif response.status_code == 404:
|
||||
# FIXED: 404 = "no information available" - successful but empty result, don't retry
|
||||
self.logger.logger.debug(f"Shodan has no information for {normalized_ip} (404)")
|
||||
result = ProviderResult() # Empty but successful result
|
||||
# Cache the empty result to avoid repeated queries
|
||||
self._save_to_cache(cache_file, result, {'error': 'No information available'})
|
||||
else:
|
||||
# Some other 404 error - treat as failure
|
||||
raise requests.exceptions.RequestException(f"Shodan API returned 404: {error_data}")
|
||||
except (ValueError, KeyError):
|
||||
# Could not parse JSON response - treat as failure
|
||||
raise requests.exceptions.RequestException(f"Shodan API returned 404 with unparseable response")
|
||||
elif cache_status == "stale":
|
||||
# If API fails on a stale cache, use the old data
|
||||
result = self._load_from_cache(cache_file)
|
||||
else:
|
||||
# Other HTTP error codes should be treated as failures
|
||||
status_code = response.status_code if response else "No response"
|
||||
raise requests.exceptions.RequestException(f"Shodan API returned HTTP {status_code}")
|
||||
empty_data = {'shodan_status': 'no_information', 'status_code': 404}
|
||||
self._save_to_cache(cache_file, result, empty_data)
|
||||
return result
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
self.logger.logger.info(f"Shodan API query returned no info for {normalized_ip}: {e}")
|
||||
elif response.status_code in [401, 403]:
|
||||
# Authentication/authorization errors - permanent failures, don't retry
|
||||
self.logger.logger.error(f"Shodan API authentication failed for {normalized_ip} (HTTP {response.status_code})")
|
||||
return ProviderResult() # Empty result, don't retry
|
||||
|
||||
elif response.status_code == 429:
|
||||
# Rate limiting - should be handled by rate limiter, but if we get here, retry
|
||||
self.logger.logger.warning(f"Shodan API rate limited for {normalized_ip} (HTTP {response.status_code})")
|
||||
if cache_status == "stale":
|
||||
result = self._load_from_cache(cache_file)
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to rate limiting")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
# Re-raise for retry scheduling - but only for actual failures
|
||||
raise e
|
||||
raise requests.exceptions.RequestException(f"Shodan API rate limited (HTTP {response.status_code}) - should retry")
|
||||
|
||||
elif response.status_code in [500, 502, 503, 504]:
|
||||
# Server errors - temporary failures that should be retried
|
||||
self.logger.logger.warning(f"Shodan API server error for {normalized_ip} (HTTP {response.status_code})")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to server error")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
raise requests.exceptions.RequestException(f"Shodan API server error (HTTP {response.status_code}) - should retry")
|
||||
|
||||
else:
|
||||
# FIXED: Other HTTP status codes - treat as no information available, don't retry
|
||||
self.logger.logger.info(f"Shodan returned status {response.status_code} for {normalized_ip} - treating as no information")
|
||||
result = ProviderResult() # Empty result
|
||||
no_info_data = {'shodan_status': 'no_information', 'status_code': response.status_code}
|
||||
self._save_to_cache(cache_file, result, no_info_data)
|
||||
return result
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
# Timeout errors - should be retried
|
||||
self.logger.logger.warning(f"Shodan API timeout for {normalized_ip}")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to timeout")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
raise # Re-raise timeout for retry
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
# Connection errors - should be retried
|
||||
self.logger.logger.warning(f"Shodan API connection error for {normalized_ip}")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to connection error")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
raise # Re-raise connection error for retry
|
||||
|
||||
except json.JSONDecodeError:
|
||||
# JSON parsing error - treat as temporary failure
|
||||
self.logger.logger.error(f"Invalid JSON response from Shodan for {normalized_ip}")
|
||||
if cache_status == "stale":
|
||||
self.logger.logger.info(f"Using stale cache for {normalized_ip} due to JSON parsing error")
|
||||
return self._load_from_cache(cache_file)
|
||||
else:
|
||||
raise requests.exceptions.RequestException("Invalid JSON response from Shodan - should retry")
|
||||
|
||||
# FIXED: Remove the generic RequestException handler that was causing 404s to retry
|
||||
# Now only specific exceptions that should be retried are re-raised
|
||||
|
||||
except Exception as e:
|
||||
# FIXED: Unexpected exceptions - log but treat as no information available, don't retry
|
||||
self.logger.logger.warning(f"Unexpected exception in Shodan query for {normalized_ip}: {e}")
|
||||
result = ProviderResult() # Empty result
|
||||
error_data = {'shodan_status': 'error', 'error': str(e)}
|
||||
self._save_to_cache(cache_file, result, error_data)
|
||||
return result
|
||||
|
||||
def _load_from_cache(self, cache_file_path: Path) -> ProviderResult:
|
||||
@@ -194,7 +306,6 @@ class ShodanProvider(BaseProvider):
|
||||
target_node=rel_data["target_node"],
|
||||
relationship_type=rel_data["relationship_type"],
|
||||
provider=rel_data["provider"],
|
||||
confidence=rel_data["confidence"],
|
||||
raw_data=rel_data.get("raw_data", {})
|
||||
)
|
||||
|
||||
@@ -206,7 +317,6 @@ class ShodanProvider(BaseProvider):
|
||||
value=attr_data["value"],
|
||||
attr_type=attr_data["type"],
|
||||
provider=attr_data["provider"],
|
||||
confidence=attr_data["confidence"],
|
||||
metadata=attr_data.get("metadata", {})
|
||||
)
|
||||
|
||||
@@ -226,7 +336,6 @@ class ShodanProvider(BaseProvider):
|
||||
"source_node": rel.source_node,
|
||||
"target_node": rel.target_node,
|
||||
"relationship_type": rel.relationship_type,
|
||||
"confidence": rel.confidence,
|
||||
"provider": rel.provider,
|
||||
"raw_data": rel.raw_data
|
||||
} for rel in result.relationships
|
||||
@@ -238,7 +347,6 @@ class ShodanProvider(BaseProvider):
|
||||
"value": attr.value,
|
||||
"type": attr.type,
|
||||
"provider": attr.provider,
|
||||
"confidence": attr.confidence,
|
||||
"metadata": attr.metadata
|
||||
} for attr in result.attributes
|
||||
]
|
||||
@@ -252,25 +360,40 @@ class ShodanProvider(BaseProvider):
|
||||
"""
|
||||
VERIFIED: Process Shodan data creating ISP nodes with ASN attributes and proper relationships.
|
||||
Enhanced to include IP version information for IPv6 addresses.
|
||||
UPDATED: Enhanced with last_seen timestamp for time-based edge coloring.
|
||||
"""
|
||||
result = ProviderResult()
|
||||
|
||||
# Determine IP version for metadata
|
||||
ip_version = get_ip_version(ip)
|
||||
|
||||
# Extract last_seen timestamp for time-based edge coloring
|
||||
last_seen = data.get('last_seen')
|
||||
|
||||
# VERIFIED: Extract ISP information and create proper ISP node with ASN
|
||||
isp_name = data.get('org')
|
||||
asn_value = data.get('asn')
|
||||
|
||||
if isp_name and asn_value:
|
||||
# Enhanced raw_data with last_seen timestamp
|
||||
raw_data = {
|
||||
'asn': asn_value,
|
||||
'shodan_org': isp_name,
|
||||
'ip_version': ip_version
|
||||
}
|
||||
|
||||
# Add last_seen timestamp if available
|
||||
if last_seen:
|
||||
raw_data['last_seen'] = last_seen
|
||||
raw_data['relevance_timestamp'] = last_seen # Standardized field for time-based coloring
|
||||
|
||||
# Create relationship from IP to ISP
|
||||
result.add_relationship(
|
||||
source_node=ip,
|
||||
target_node=isp_name,
|
||||
relationship_type='shodan_isp',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
raw_data={'asn': asn_value, 'shodan_org': isp_name, 'ip_version': ip_version}
|
||||
raw_data=raw_data
|
||||
)
|
||||
|
||||
# Add ASN as attribute to the ISP node
|
||||
@@ -280,7 +403,6 @@ class ShodanProvider(BaseProvider):
|
||||
value=asn_value,
|
||||
attr_type='isp_info',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
metadata={'description': 'Autonomous System Number from Shodan', 'ip_version': ip_version}
|
||||
)
|
||||
|
||||
@@ -291,7 +413,6 @@ class ShodanProvider(BaseProvider):
|
||||
value=isp_name,
|
||||
attr_type='isp_info',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
metadata={'description': 'Organization name from Shodan', 'ip_version': ip_version}
|
||||
)
|
||||
|
||||
@@ -306,20 +427,24 @@ class ShodanProvider(BaseProvider):
|
||||
else:
|
||||
relationship_type = 'shodan_a_record'
|
||||
|
||||
# Enhanced raw_data with last_seen timestamp
|
||||
hostname_raw_data = {**data, 'ip_version': ip_version}
|
||||
if last_seen:
|
||||
hostname_raw_data['last_seen'] = last_seen
|
||||
hostname_raw_data['relevance_timestamp'] = last_seen
|
||||
|
||||
result.add_relationship(
|
||||
source_node=ip,
|
||||
target_node=hostname,
|
||||
relationship_type=relationship_type,
|
||||
provider=self.name,
|
||||
confidence=0.8,
|
||||
raw_data={**data, 'ip_version': ip_version}
|
||||
raw_data=hostname_raw_data
|
||||
)
|
||||
self.log_relationship_discovery(
|
||||
source_node=ip,
|
||||
target_node=hostname,
|
||||
relationship_type=relationship_type,
|
||||
confidence_score=0.8,
|
||||
raw_data={**data, 'ip_version': ip_version},
|
||||
raw_data=hostname_raw_data,
|
||||
discovery_method=f"shodan_host_lookup_ipv{ip_version}"
|
||||
)
|
||||
elif key == 'ports':
|
||||
@@ -331,7 +456,6 @@ class ShodanProvider(BaseProvider):
|
||||
value=port,
|
||||
attr_type='shodan_network_info',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
metadata={'ip_version': ip_version}
|
||||
)
|
||||
elif isinstance(value, (str, int, float, bool)) and value is not None:
|
||||
@@ -342,7 +466,6 @@ class ShodanProvider(BaseProvider):
|
||||
value=value,
|
||||
attr_type='shodan_info',
|
||||
provider=self.name,
|
||||
confidence=0.9,
|
||||
metadata={'ip_version': ip_version}
|
||||
)
|
||||
|
||||
|
||||
@@ -8,3 +8,4 @@ dnspython
|
||||
gunicorn
|
||||
redis
|
||||
python-dotenv
|
||||
psycopg2-binary
|
||||
@@ -1,4 +1,4 @@
|
||||
/* DNSRecon - Optimized Compact Theme */
|
||||
/* DNScope - Optimized Compact Theme */
|
||||
|
||||
/* Reset and Base */
|
||||
* {
|
||||
@@ -326,6 +326,20 @@ input[type="text"]:focus, select:focus {
|
||||
animation: progressGlow 2s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
.gradient-bar {
|
||||
height: 4px;
|
||||
background: linear-gradient(to right, #6b7280, #00bfff);
|
||||
border-radius: 2px;
|
||||
margin: 0.2rem 0;
|
||||
}
|
||||
|
||||
.gradient-labels {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 0.6rem;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
@keyframes progressShimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(100%); }
|
||||
@@ -380,32 +394,59 @@ input[type="text"]:focus, select:focus {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
/* Graph Controls */
|
||||
/* Enhanced graph controls layout */
|
||||
.graph-controls {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: rgba(26, 26, 26, 0.9);
|
||||
padding: 0.5rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #444;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
|
||||
z-index: 100;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.graph-control-btn, .btn-icon-small {
|
||||
background: rgba(42, 42, 42, 0.9);
|
||||
.graph-control-btn {
|
||||
background: linear-gradient(135deg, #2a2a2a 0%, #1e1e1e 100%);
|
||||
border: 1px solid #555;
|
||||
color: #c7c7c7;
|
||||
padding: 0.3rem 0.5rem;
|
||||
font-family: 'Roboto Mono', monospace;
|
||||
font-size: 0.7rem;
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-family: 'Roboto Mono', monospace;
|
||||
font-size: 0.8rem;
|
||||
transition: all 0.2s ease;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.graph-control-btn:hover, .btn-icon-small:hover {
|
||||
.graph-control-btn:hover {
|
||||
background: linear-gradient(135deg, #3a3a3a 0%, #2e2e2e 100%);
|
||||
border-color: #00ff41;
|
||||
color: #00ff41;
|
||||
}
|
||||
|
||||
.graph-control-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.manual-refresh-btn {
|
||||
background: linear-gradient(135deg, #4a4a2a 0%, #3e3e1e 100%);
|
||||
border-color: #ffaa00;
|
||||
color: #ffaa00;
|
||||
}
|
||||
|
||||
.manual-refresh-btn:hover {
|
||||
background: linear-gradient(135deg, #5a5a3a 0%, #4e4e2e 100%);
|
||||
color: #ffcc33;
|
||||
border-color: #ffcc33;
|
||||
}
|
||||
|
||||
.graph-filter-panel {
|
||||
position: absolute;
|
||||
bottom: 8px;
|
||||
@@ -474,6 +515,7 @@ input[type="text"]:focus, select:focus {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
align-items: center;
|
||||
max-height: 3rem;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
@@ -499,14 +541,6 @@ input[type="text"]:focus, select:focus {
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
.legend-edge.high-confidence {
|
||||
background: #00ff41;
|
||||
}
|
||||
|
||||
.legend-edge.medium-confidence {
|
||||
background: #ff9900;
|
||||
}
|
||||
|
||||
/* Provider Panel */
|
||||
.provider-panel {
|
||||
grid-area: providers;
|
||||
@@ -986,11 +1020,6 @@ input[type="text"]:focus, select:focus {
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.confidence-indicator {
|
||||
font-size: 0.6rem;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.node-link-compact {
|
||||
color: #00aaff;
|
||||
text-decoration: none;
|
||||
@@ -1094,6 +1123,56 @@ input[type="text"]:focus, select:focus {
|
||||
border-left: 3px solid #00aaff;
|
||||
}
|
||||
|
||||
.time-control-container {
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
background: rgba(42, 42, 42, 0.3);
|
||||
border-radius: 4px;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.time-control-label {
|
||||
font-size: 0.8rem;
|
||||
color: #c7c7c7;
|
||||
margin-bottom: 0.3rem;
|
||||
display: block;
|
||||
font-family: 'Roboto Mono', monospace;
|
||||
}
|
||||
|
||||
.time-control-input {
|
||||
width: 100%;
|
||||
padding: 0.3rem;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #555;
|
||||
border-radius: 3px;
|
||||
color: #c7c7c7;
|
||||
font-family: 'Roboto Mono', monospace;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.time-control-input:focus {
|
||||
outline: none;
|
||||
border-color: #00ff41;
|
||||
box-shadow: 0 0 5px rgba(0, 255, 65, 0.3);
|
||||
}
|
||||
|
||||
.time-gradient-info {
|
||||
font-size: 0.7rem;
|
||||
color: #999;
|
||||
margin-top: 0.3rem;
|
||||
text-align: center;
|
||||
font-family: 'Roboto Mono', monospace;
|
||||
}
|
||||
|
||||
/* Edge color legend for time-based gradient */
|
||||
.time-gradient-legend {
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.3rem;
|
||||
background: rgba(26, 26, 26, 0.5);
|
||||
border-radius: 3px;
|
||||
border: 1px solid #333;
|
||||
}
|
||||
|
||||
/* Settings Modal Specific */
|
||||
.provider-toggle {
|
||||
appearance: none !important;
|
||||
@@ -1323,4 +1402,16 @@ input[type="password"]:focus {
|
||||
.provider-list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.graph-controls {
|
||||
position: relative;
|
||||
top: auto;
|
||||
right: auto;
|
||||
margin-bottom: 1rem;
|
||||
min-width: auto;
|
||||
}
|
||||
|
||||
.time-control-input {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
}
|
||||
1210
static/js/graph.js
1210
static/js/graph.js
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,16 @@
|
||||
/**
|
||||
* Main application logic for DNSRecon web interface
|
||||
* Main application logic for DNScope web interface
|
||||
* Handles UI interactions, API communication, and data flow
|
||||
* UPDATED: Now compatible with a strictly flat, unified data model for attributes.
|
||||
*/
|
||||
|
||||
class DNSReconApp {
|
||||
class DNScopeApp {
|
||||
constructor() {
|
||||
console.log('DNSReconApp constructor called');
|
||||
console.log('DNScopeApp constructor called');
|
||||
this.graphManager = null;
|
||||
this.scanStatus = 'idle';
|
||||
this.pollInterval = null;
|
||||
this.statusPollInterval = null; // Separate status polling
|
||||
this.graphPollInterval = null; // Separate graph polling
|
||||
this.currentSessionId = null;
|
||||
|
||||
this.elements = {};
|
||||
@@ -17,6 +18,10 @@ class DNSReconApp {
|
||||
this.isScanning = false;
|
||||
this.lastGraphUpdate = null;
|
||||
|
||||
// Graph polling optimization
|
||||
this.graphPollingNodeThreshold = 500; // Default, will be loaded from config
|
||||
this.graphPollingEnabled = true;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
@@ -24,7 +29,7 @@ class DNSReconApp {
|
||||
* Initialize the application
|
||||
*/
|
||||
init() {
|
||||
console.log('DNSReconApp init called');
|
||||
console.log('DNScopeApp init called');
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('DOM loaded, initializing application...');
|
||||
try {
|
||||
@@ -35,17 +40,33 @@ class DNSReconApp {
|
||||
this.loadProviders();
|
||||
this.initializeEnhancedModals();
|
||||
this.addCheckboxStyling();
|
||||
this.loadConfig(); // Load configuration including threshold
|
||||
|
||||
this.updateGraph();
|
||||
|
||||
console.log('DNSRecon application initialized successfully');
|
||||
console.log('DNScope application initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize DNSRecon application:', error);
|
||||
console.error('Failed to initialize DNScope application:', error);
|
||||
this.showError(`Initialization failed: ${error.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configuration from backend
|
||||
*/
|
||||
async loadConfig() {
|
||||
try {
|
||||
const response = await this.apiCall('/api/config');
|
||||
if (response.success) {
|
||||
this.graphPollingNodeThreshold = response.config.graph_polling_node_threshold;
|
||||
console.log(`Graph polling threshold set to: ${this.graphPollingNodeThreshold} nodes`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load config, using defaults:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize DOM element references
|
||||
*/
|
||||
@@ -62,6 +83,8 @@ class DNSReconApp {
|
||||
exportModal: document.getElementById('export-modal'),
|
||||
exportModalClose: document.getElementById('export-modal-close'),
|
||||
exportGraphJson: document.getElementById('export-graph-json'),
|
||||
exportTargetsTxt: document.getElementById('export-targets-txt'),
|
||||
exportExecutiveSummary: document.getElementById('export-executive-summary'),
|
||||
configureSettings: document.getElementById('configure-settings'),
|
||||
|
||||
// Status elements
|
||||
@@ -165,6 +188,12 @@ class DNSReconApp {
|
||||
if (this.elements.exportGraphJson) {
|
||||
this.elements.exportGraphJson.addEventListener('click', () => this.exportGraphJson());
|
||||
}
|
||||
if (this.elements.exportTargetsTxt) {
|
||||
this.elements.exportTargetsTxt.addEventListener('click', () => this.exportTargetsTxt());
|
||||
}
|
||||
if (this.elements.exportExecutiveSummary) {
|
||||
this.elements.exportExecutiveSummary.addEventListener('click', () => this.exportExecutiveSummary());
|
||||
}
|
||||
|
||||
|
||||
this.elements.configureSettings.addEventListener('click', () => this.showSettingsModal());
|
||||
@@ -195,12 +224,6 @@ class DNSReconApp {
|
||||
if (e.target === this.elements.settingsModal) this.hideSettingsModal();
|
||||
});
|
||||
}
|
||||
if (this.elements.saveApiKeys) {
|
||||
this.elements.saveApiKeys.removeEventListener('click', this.saveApiKeys);
|
||||
}
|
||||
if (this.elements.resetApiKeys) {
|
||||
this.elements.resetApiKeys.removeEventListener('click', this.resetApiKeys);
|
||||
}
|
||||
|
||||
// Setup new handlers
|
||||
const saveSettingsBtn = document.getElementById('save-settings');
|
||||
@@ -255,12 +278,19 @@ class DNSReconApp {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize graph visualization
|
||||
* Initialize graph visualization with manual refresh button
|
||||
*/
|
||||
initializeGraph() {
|
||||
try {
|
||||
console.log('Initializing graph manager...');
|
||||
this.graphManager = new GraphManager('network-graph');
|
||||
|
||||
// Set up manual refresh handler
|
||||
this.graphManager.setManualRefreshHandler(() => {
|
||||
console.log('Manual graph refresh requested');
|
||||
this.updateGraph();
|
||||
});
|
||||
|
||||
console.log('Graph manager initialized successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize graph manager:', error);
|
||||
@@ -268,6 +298,34 @@ class DNSReconApp {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if graph polling should be enabled based on node count
|
||||
*/
|
||||
shouldEnableGraphPolling() {
|
||||
if (!this.graphManager || !this.graphManager.nodes) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const nodeCount = this.graphManager.nodes.length;
|
||||
return nodeCount <= this.graphPollingNodeThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update manual refresh button visibility and state.
|
||||
* The button will be visible whenever auto-polling is disabled,
|
||||
* and enabled only when a scan is in progress.
|
||||
*/
|
||||
updateManualRefreshButton() {
|
||||
if (!this.graphManager || !this.graphManager.manualRefreshButton) return;
|
||||
|
||||
const shouldShow = !this.graphPollingEnabled;
|
||||
this.graphManager.showManualRefreshButton(shouldShow);
|
||||
|
||||
if (shouldShow) {
|
||||
this.graphManager.manualRefreshButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start scan with error handling
|
||||
*/
|
||||
@@ -316,18 +374,21 @@ class DNSReconApp {
|
||||
|
||||
if (clearGraph) {
|
||||
this.graphManager.clear();
|
||||
this.graphPollingEnabled = true; // Reset polling when starting fresh
|
||||
}
|
||||
|
||||
console.log(`Scan started for ${target} with depth ${maxDepth}`);
|
||||
|
||||
// Start polling immediately with faster interval for responsiveness
|
||||
this.startPolling(1000);
|
||||
// Start optimized polling
|
||||
this.startOptimizedPolling();
|
||||
|
||||
// Force an immediate status update
|
||||
console.log('Forcing immediate status update...');
|
||||
setTimeout(() => {
|
||||
this.updateStatus();
|
||||
if (this.graphPollingEnabled) {
|
||||
this.updateGraph();
|
||||
}
|
||||
}, 100);
|
||||
|
||||
} else {
|
||||
@@ -340,6 +401,35 @@ class DNSReconApp {
|
||||
this.setUIState('idle');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start optimized polling with separate status and graph intervals
|
||||
*/
|
||||
startOptimizedPolling() {
|
||||
console.log('=== STARTING OPTIMIZED POLLING ===');
|
||||
|
||||
this.stopPolling(); // Stop any existing polling
|
||||
|
||||
// Always poll status for progress bar
|
||||
this.statusPollInterval = setInterval(() => {
|
||||
this.updateStatus();
|
||||
this.loadProviders();
|
||||
}, 2000);
|
||||
|
||||
// Only poll graph if enabled
|
||||
if (this.graphPollingEnabled) {
|
||||
this.graphPollInterval = setInterval(() => {
|
||||
this.updateGraph();
|
||||
}, 2000);
|
||||
console.log('Graph polling started');
|
||||
} else {
|
||||
console.log('Graph polling disabled due to node count');
|
||||
}
|
||||
|
||||
this.updateManualRefreshButton();
|
||||
console.log(`Optimized polling started - Status: enabled, Graph: ${this.graphPollingEnabled ? 'enabled' : 'disabled'}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan stop with immediate UI feedback
|
||||
*/
|
||||
@@ -366,15 +456,8 @@ class DNSReconApp {
|
||||
this.updateStatus();
|
||||
}, 100);
|
||||
|
||||
// Continue polling for a bit to catch the status change
|
||||
this.startPolling(500); // Fast polling to catch status change
|
||||
|
||||
// Stop fast polling after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (this.scanStatus === 'stopped' || this.scanStatus === 'idle') {
|
||||
this.stopPolling();
|
||||
}
|
||||
}, 10000);
|
||||
// Continue status polling for a bit to catch the status change
|
||||
// No need to resume graph polling
|
||||
|
||||
} else {
|
||||
throw new Error(response.error || 'Failed to stop scan');
|
||||
@@ -450,7 +533,7 @@ class DNSReconApp {
|
||||
|
||||
// Get the filename from headers or create one
|
||||
const contentDisposition = response.headers.get('content-disposition');
|
||||
let filename = 'dnsrecon_export.json';
|
||||
let filename = 'DNScope_export.json';
|
||||
if (contentDisposition) {
|
||||
const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
|
||||
if (filenameMatch) {
|
||||
@@ -486,6 +569,60 @@ class DNSReconApp {
|
||||
}
|
||||
}
|
||||
|
||||
async exportTargetsTxt() {
|
||||
await this.exportFile('/api/export/targets', this.elements.exportTargetsTxt, 'Exporting Targets...');
|
||||
}
|
||||
|
||||
async exportExecutiveSummary() {
|
||||
await this.exportFile('/api/export/summary', this.elements.exportExecutiveSummary, 'Generating Summary...');
|
||||
}
|
||||
|
||||
async exportFile(endpoint, buttonElement, loadingMessage) {
|
||||
try {
|
||||
console.log(`Exporting from ${endpoint}...`);
|
||||
|
||||
const originalContent = buttonElement.innerHTML;
|
||||
buttonElement.innerHTML = `<span class="btn-icon">[...]</span><span>${loadingMessage}</span>`;
|
||||
buttonElement.disabled = true;
|
||||
|
||||
const response = await fetch(endpoint, { method: 'GET' });
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const contentDisposition = response.headers.get('content-disposition');
|
||||
let filename = 'export.txt';
|
||||
if (contentDisposition) {
|
||||
const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
|
||||
if (filenameMatch) {
|
||||
filename = filenameMatch[1].replace(/['"]/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
this.showSuccess('File exported successfully');
|
||||
this.hideExportModal();
|
||||
} catch (error) {
|
||||
console.error(`Failed to export from ${endpoint}:`, error);
|
||||
this.showError(`Export failed: ${error.message}`);
|
||||
} finally {
|
||||
const originalContent = buttonElement._originalContent || buttonElement.innerHTML;
|
||||
buttonElement.innerHTML = originalContent;
|
||||
buttonElement.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling for scan updates with configurable interval
|
||||
*/
|
||||
@@ -511,10 +648,18 @@ class DNSReconApp {
|
||||
*/
|
||||
stopPolling() {
|
||||
console.log('=== STOPPING POLLING ===');
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
this.pollInterval = null;
|
||||
|
||||
if (this.statusPollInterval) {
|
||||
clearInterval(this.statusPollInterval);
|
||||
this.statusPollInterval = null;
|
||||
}
|
||||
|
||||
if (this.graphPollInterval) {
|
||||
clearInterval(this.graphPollInterval);
|
||||
this.graphPollInterval = null;
|
||||
}
|
||||
|
||||
this.updateManualRefreshButton();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -549,7 +694,7 @@ class DNSReconApp {
|
||||
}
|
||||
|
||||
/**
|
||||
* Update graph from server
|
||||
* Update graph from server with polling optimization
|
||||
*/
|
||||
async updateGraph() {
|
||||
try {
|
||||
@@ -564,11 +709,29 @@ class DNSReconApp {
|
||||
console.log('- Nodes:', graphData.nodes ? graphData.nodes.length : 0);
|
||||
console.log('- Edges:', graphData.edges ? graphData.edges.length : 0);
|
||||
|
||||
// FIXED: Always update graph, even if empty - let GraphManager handle placeholder
|
||||
// Always update graph, even if empty - let GraphManager handle placeholder
|
||||
if (this.graphManager) {
|
||||
this.graphManager.updateGraph(graphData);
|
||||
this.lastGraphUpdate = Date.now();
|
||||
|
||||
// Check if we should disable graph polling after this update
|
||||
const nodeCount = graphData.nodes ? graphData.nodes.length : 0;
|
||||
const shouldEnablePolling = nodeCount <= this.graphPollingNodeThreshold;
|
||||
|
||||
if (this.graphPollingEnabled && !shouldEnablePolling) {
|
||||
console.log(`Graph polling disabled: ${nodeCount} nodes exceeds threshold of ${this.graphPollingNodeThreshold}`);
|
||||
this.graphPollingEnabled = false;
|
||||
this.showWarning(`Graph auto-refresh disabled: ${nodeCount} nodes exceed threshold of ${this.graphPollingNodeThreshold}. Use manual refresh button.`);
|
||||
|
||||
// Stop graph polling but keep status polling
|
||||
if (this.graphPollInterval) {
|
||||
clearInterval(this.graphPollInterval);
|
||||
this.graphPollInterval = null;
|
||||
}
|
||||
|
||||
this.updateManualRefreshButton();
|
||||
}
|
||||
|
||||
// Update relationship count in status
|
||||
const edgeCount = graphData.edges ? graphData.edges.length : 0;
|
||||
if (this.elements.relationshipsDisplay) {
|
||||
@@ -577,7 +740,7 @@ class DNSReconApp {
|
||||
}
|
||||
} else {
|
||||
console.error('Graph update failed:', response);
|
||||
// FIXED: Show placeholder when graph update fails
|
||||
// Show placeholder when graph update fails
|
||||
if (this.graphManager && this.graphManager.container) {
|
||||
const placeholder = this.graphManager.container.querySelector('.graph-placeholder');
|
||||
if (placeholder) {
|
||||
@@ -588,7 +751,7 @@ class DNSReconApp {
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to update graph:', error);
|
||||
// FIXED: Show placeholder on error
|
||||
// Show placeholder on error
|
||||
if (this.graphManager && this.graphManager.container) {
|
||||
const placeholder = this.graphManager.container.querySelector('.graph-placeholder');
|
||||
if (placeholder) {
|
||||
@@ -598,7 +761,6 @@ class DNSReconApp {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update status display elements
|
||||
* @param {Object} status - Status object from server
|
||||
@@ -675,8 +837,6 @@ class DNSReconApp {
|
||||
case 'running':
|
||||
this.setUIState('scanning', task_queue_size);
|
||||
this.showSuccess('Scan is running');
|
||||
// Increase polling frequency for active scans
|
||||
this.startPolling(1000); // Poll every 1 second for running scans
|
||||
this.updateConnectionStatus('active');
|
||||
break;
|
||||
|
||||
@@ -686,9 +846,10 @@ class DNSReconApp {
|
||||
this.showSuccess('Scan completed successfully');
|
||||
this.updateConnectionStatus('completed');
|
||||
this.loadProviders();
|
||||
// Force a final graph update
|
||||
console.log('Scan completed - forcing final graph update');
|
||||
setTimeout(() => this.updateGraph(), 100);
|
||||
|
||||
// Do final graph update when scan completes
|
||||
console.log('Scan completed - performing final graph update');
|
||||
setTimeout(() => this.updateGraph(), 1000);
|
||||
break;
|
||||
|
||||
case 'failed':
|
||||
@@ -758,6 +919,7 @@ class DNSReconApp {
|
||||
|
||||
switch (state) {
|
||||
case 'scanning':
|
||||
case 'running':
|
||||
this.isScanning = true;
|
||||
if (this.graphManager) {
|
||||
this.graphManager.isScanning = true;
|
||||
@@ -790,12 +952,12 @@ class DNSReconApp {
|
||||
this.graphManager.isScanning = false;
|
||||
}
|
||||
if (this.elements.startScan) {
|
||||
this.elements.startScan.disabled = !isQueueEmpty;
|
||||
this.elements.startScan.disabled = false;
|
||||
this.elements.startScan.classList.remove('loading');
|
||||
this.elements.startScan.innerHTML = '<span class="btn-icon">[RUN]</span><span>Start Reconnaissance</span>';
|
||||
}
|
||||
if (this.elements.addToGraph) {
|
||||
this.elements.addToGraph.disabled = !isQueueEmpty;
|
||||
this.elements.addToGraph.disabled = false;
|
||||
this.elements.addToGraph.classList.remove('loading');
|
||||
}
|
||||
if (this.elements.stopScan) {
|
||||
@@ -805,6 +967,9 @@ class DNSReconApp {
|
||||
if (this.elements.targetInput) this.elements.targetInput.disabled = false;
|
||||
if (this.elements.maxDepth) this.elements.maxDepth.disabled = false;
|
||||
if (this.elements.configureSettings) this.elements.configureSettings.disabled = false;
|
||||
|
||||
// Update manual refresh button visibility
|
||||
this.updateManualRefreshButton();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1335,11 +1500,32 @@ class DNSReconApp {
|
||||
}
|
||||
|
||||
/**
|
||||
* UPDATED: Generate details for standard nodes with organized attribute grouping
|
||||
* UPDATED: Generate details for standard nodes with organized attribute grouping and data warnings
|
||||
*/
|
||||
generateStandardNodeDetails(node) {
|
||||
let html = '';
|
||||
|
||||
// Check for and display a crt.sh data warning if it exists
|
||||
const crtshWarningAttr = this.findAttributeByName(node.attributes, 'crtsh_data_warning');
|
||||
if (crtshWarningAttr) {
|
||||
html += `
|
||||
<div class="modal-section" style="border-left: 3px solid #ff9900; background: rgba(255, 153, 0, 0.05);">
|
||||
<details open>
|
||||
<summary style="color: #ff9900;">
|
||||
<span>⚠️ Data Integrity Warning</span>
|
||||
</summary>
|
||||
<div class="modal-section-content">
|
||||
<p class="placeholder-subtext" style="color: #e0e0e0; font-size: 0.8rem; line-height: 1.5;">
|
||||
${this.escapeHtml(crtshWarningAttr.value)}
|
||||
<br><br>
|
||||
This can occur for very large domains (e.g., google.com) where crt.sh may return a limited subset of all available certificates. As a result, the certificate status may not be fully representative.
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Relationships sections
|
||||
html += this.generateRelationshipsSection(node);
|
||||
|
||||
@@ -1357,6 +1543,19 @@ class DNSReconApp {
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to find an attribute by name in the standardized attributes list
|
||||
* @param {Array} attributes - List of StandardAttribute objects
|
||||
* @param {string} name - Attribute name to find
|
||||
* @returns {Object|null} The attribute object if found, null otherwise
|
||||
*/
|
||||
findAttributeByName(attributes, name) {
|
||||
if (!Array.isArray(attributes)) {
|
||||
return null;
|
||||
}
|
||||
return attributes.find(attr => attr.name === name) || null;
|
||||
}
|
||||
|
||||
generateOrganizedAttributesSection(attributes, nodeType) {
|
||||
if (!Array.isArray(attributes) || attributes.length === 0) {
|
||||
return '';
|
||||
@@ -1517,17 +1716,9 @@ class DNSReconApp {
|
||||
return groups;
|
||||
}
|
||||
|
||||
formatEdgeLabel(relationshipType, confidence) {
|
||||
if (!relationshipType) return '';
|
||||
|
||||
const confidenceText = confidence >= 0.8 ? '●' : confidence >= 0.6 ? '◐' : '○';
|
||||
return `${relationshipType} ${confidenceText}`;
|
||||
}
|
||||
|
||||
createEdgeTooltip(edge) {
|
||||
let tooltip = `<div style="font-family: 'Roboto Mono', monospace; font-size: 11px;">`;
|
||||
tooltip += `<div style="color: #00ff41; font-weight: bold; margin-bottom: 4px;">${edge.label || 'Relationship'}</div>`;
|
||||
tooltip += `<div style="color: #999; margin-bottom: 2px;">Confidence: ${(edge.confidence_score * 100).toFixed(1)}%</div>`;
|
||||
|
||||
// UPDATED: Use raw provider name (no formatting)
|
||||
if (edge.source_provider) {
|
||||
@@ -1547,15 +1738,19 @@ class DNSReconApp {
|
||||
* UPDATED: Enhanced correlation details showing the correlated attribute clearly (no formatting)
|
||||
*/
|
||||
generateCorrelationDetails(node) {
|
||||
const metadata = node.metadata || {};
|
||||
const value = metadata.value;
|
||||
const attributes = node.attributes || [];
|
||||
const correlationValueAttr = attributes.find(attr => attr.name === 'correlation_value');
|
||||
const value = correlationValueAttr ? correlationValueAttr.value : 'Unknown';
|
||||
|
||||
const metadataAttr = attributes.find(attr => attr.name === 'correlation_value');
|
||||
const metadata = metadataAttr ? metadataAttr.metadata : {};
|
||||
const correlatedNodes = metadata.correlated_nodes || [];
|
||||
const sources = metadata.sources || [];
|
||||
|
||||
let html = '';
|
||||
|
||||
// Show what attribute is being correlated (raw names)
|
||||
const primarySource = metadata.primary_source || 'unknown';
|
||||
const primarySource = sources.length > 0 ? sources[0].attribute : 'unknown';
|
||||
|
||||
html += `
|
||||
<div class="modal-section">
|
||||
@@ -1663,7 +1858,7 @@ class DNSReconApp {
|
||||
html += `
|
||||
<div class="relationship-compact-item">
|
||||
<span class="node-link-compact" data-node-id="${innerNodeId}">${innerNodeId}</span>
|
||||
<button class="btn-icon-small extract-node-btn"
|
||||
<button class="graph-control-btn extract-node-btn"
|
||||
title="Extract to graph"
|
||||
data-large-entity-id="${largeEntityId}"
|
||||
data-node-id="${innerNodeId}">[+]</button>
|
||||
@@ -1690,8 +1885,6 @@ class DNSReconApp {
|
||||
`;
|
||||
|
||||
node.incoming_edges.forEach(edge => {
|
||||
const confidence = edge.data.confidence_score || 0;
|
||||
const confidenceClass = confidence >= 0.8 ? 'high' : confidence >= 0.6 ? 'medium' : 'low';
|
||||
|
||||
html += `
|
||||
<div class="relationship-item">
|
||||
@@ -1700,9 +1893,6 @@ class DNSReconApp {
|
||||
</div>
|
||||
<div class="relationship-type">
|
||||
<span class="relation-label">${edge.data.relationship_type}</span>
|
||||
<span class="confidence-indicator confidence-${confidenceClass}" title="Confidence: ${(confidence * 100).toFixed(1)}%">
|
||||
${'●'.repeat(Math.ceil(confidence * 3))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -1721,9 +1911,6 @@ class DNSReconApp {
|
||||
`;
|
||||
|
||||
node.outgoing_edges.forEach(edge => {
|
||||
const confidence = edge.data.confidence_score || 0;
|
||||
const confidenceClass = confidence >= 0.8 ? 'high' : confidence >= 0.6 ? 'medium' : 'low';
|
||||
|
||||
html += `
|
||||
<div class="relationship-item">
|
||||
<div class="relationship-target node-link" data-node-id="${edge.to}">
|
||||
@@ -1731,9 +1918,6 @@ class DNSReconApp {
|
||||
</div>
|
||||
<div class="relationship-type">
|
||||
<span class="relation-label">${edge.data.relationship_type}</span>
|
||||
<span class="confidence-indicator confidence-${confidenceClass}" title="Confidence: ${(confidence * 100).toFixed(1)}%">
|
||||
${'●'.repeat(Math.ceil(confidence * 3))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -1923,6 +2107,16 @@ class DNSReconApp {
|
||||
|
||||
async extractNode(largeEntityId, nodeId) {
|
||||
try {
|
||||
console.log(`Extracting node ${nodeId} from large entity ${largeEntityId}`);
|
||||
|
||||
// Show immediate feedback
|
||||
const button = document.querySelector(`[data-node-id="${nodeId}"][data-large-entity-id="${largeEntityId}"]`);
|
||||
if (button) {
|
||||
const originalContent = button.innerHTML;
|
||||
button.innerHTML = '[...]';
|
||||
button.disabled = true;
|
||||
}
|
||||
|
||||
const response = await this.apiCall('/api/graph/large-entity/extract', 'POST', {
|
||||
large_entity_id: largeEntityId,
|
||||
node_id: nodeId,
|
||||
@@ -1931,15 +2125,32 @@ class DNSReconApp {
|
||||
if (response.success) {
|
||||
this.showSuccess(response.message);
|
||||
|
||||
this.hideModal();
|
||||
// FIXED: Don't update local modal data - let backend be source of truth
|
||||
// Force immediate graph update to get fresh backend data
|
||||
console.log('Extraction successful, updating graph with fresh backend data');
|
||||
await this.updateGraph();
|
||||
|
||||
// If the scanner was idle, it's now running. Start polling to see the new node appear.
|
||||
if (this.scanStatus === 'idle') {
|
||||
this.startPolling(1000);
|
||||
} else {
|
||||
// If already scanning, force a quick graph update to see the change sooner.
|
||||
setTimeout(() => this.updateGraph(), 500);
|
||||
// FIXED: Re-fetch graph data instead of manipulating local state
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const graphResponse = await this.apiCall('/api/graph');
|
||||
if (graphResponse.success) {
|
||||
this.graphManager.updateGraph(graphResponse.graph);
|
||||
|
||||
// Update modal with fresh data if still open
|
||||
if (this.elements.nodeModal && this.elements.nodeModal.style.display === 'block') {
|
||||
if (this.graphManager.nodes) {
|
||||
const updatedLargeEntity = this.graphManager.nodes.get(largeEntityId);
|
||||
if (updatedLargeEntity) {
|
||||
this.showNodeModal(updatedLargeEntity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error refreshing graph after extraction:', error);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
} else {
|
||||
throw new Error(response.error || 'Extraction failed on the server.');
|
||||
@@ -1947,6 +2158,13 @@ class DNSReconApp {
|
||||
} catch (error) {
|
||||
console.error('Failed to extract node:', error);
|
||||
this.showError(`Extraction failed: ${error.message}`);
|
||||
|
||||
// Restore button state on error
|
||||
const button = document.querySelector(`[data-node-id="${nodeId}"][data-large-entity-id="${largeEntityId}"]`);
|
||||
if (button) {
|
||||
button.innerHTML = '[+]';
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2119,51 +2337,6 @@ class DNSReconApp {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save API Keys
|
||||
*/
|
||||
async saveApiKeys() {
|
||||
const inputs = this.elements.apiKeyInputs.querySelectorAll('input');
|
||||
const keys = {};
|
||||
inputs.forEach(input => {
|
||||
const provider = input.dataset.provider;
|
||||
const value = input.value.trim();
|
||||
if (provider && value) {
|
||||
keys[provider] = value;
|
||||
}
|
||||
});
|
||||
|
||||
if (Object.keys(keys).length === 0) {
|
||||
this.showWarning('No API keys were entered.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.apiCall('/api/config/api-keys', 'POST', keys);
|
||||
if (response.success) {
|
||||
this.showSuccess(response.message);
|
||||
this.hideSettingsModal();
|
||||
this.loadProviders(); // Refresh provider status
|
||||
} else {
|
||||
throw new Error(response.error || 'Failed to save API keys');
|
||||
}
|
||||
} catch (error) {
|
||||
this.showError(`Error saving API keys: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset API Key fields
|
||||
*/
|
||||
resetApiKeys() {
|
||||
const inputs = this.elements.apiKeyInputs.querySelectorAll('input');
|
||||
inputs.forEach(input => {
|
||||
input.value = '';
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Make API call to server
|
||||
* @param {string} endpoint - API endpoint
|
||||
@@ -2546,5 +2719,5 @@ style.textContent = `
|
||||
document.head.appendChild(style);
|
||||
|
||||
// Initialize application when page loads
|
||||
console.log('Creating DNSReconApp instance...');
|
||||
const app = new DNSReconApp();
|
||||
console.log('Creating DNScopeApp instance...');
|
||||
const app = new DNScopeApp();
|
||||
@@ -4,7 +4,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>DNSRecon - Infrastructure Reconnaissance</title>
|
||||
<title>DNScope - Infrastructure Reconnaissance</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" type="text/css">
|
||||
@@ -18,8 +18,8 @@
|
||||
<header class="header">
|
||||
<div class="header-content">
|
||||
<div class="logo">
|
||||
<span class="logo-icon">[DNS]</span>
|
||||
<span class="logo-text">RECON</span>
|
||||
<span class="logo-icon">[DN]</span>
|
||||
<span class="logo-text">Scope</span>
|
||||
</div>
|
||||
<div class="status-indicator">
|
||||
<span id="connection-status" class="status-dot"></span>
|
||||
@@ -194,7 +194,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Settings Modal -->
|
||||
<div id="settings-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -203,7 +202,6 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="modal-details">
|
||||
<!-- Scan Settings Section -->
|
||||
<section class="modal-section">
|
||||
<details open>
|
||||
<summary>
|
||||
@@ -224,7 +222,6 @@
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<!-- Provider Configuration Section -->
|
||||
<section class="modal-section">
|
||||
<details open>
|
||||
<summary>
|
||||
@@ -233,13 +230,11 @@
|
||||
</summary>
|
||||
<div class="modal-section-content">
|
||||
<div id="provider-config-list">
|
||||
<!-- Dynamically populated -->
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<!-- API Keys Section -->
|
||||
<section class="modal-section">
|
||||
<details>
|
||||
<summary>
|
||||
@@ -252,13 +247,11 @@
|
||||
Only provide API keys you don't use for anything else.
|
||||
</p>
|
||||
<div id="api-key-inputs">
|
||||
<!-- Dynamically populated -->
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="button-group" style="margin-top: 1.5rem;">
|
||||
<button id="save-settings" class="btn btn-primary">
|
||||
<span class="btn-icon">[SAVE]</span>
|
||||
@@ -274,7 +267,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Export Modal -->
|
||||
<div id="export-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -299,6 +291,20 @@
|
||||
provider statistics, and scan metadata in JSON format for analysis and
|
||||
archival.</span>
|
||||
</div>
|
||||
<button id="export-targets-txt" class="btn btn-primary" style="margin-top: 1rem;">
|
||||
<span class="btn-icon">[TXT]</span>
|
||||
<span>Export Targets</span>
|
||||
</button>
|
||||
<div class="status-row" style="margin-top: 0.5rem;">
|
||||
<span class="status-label">A simple text file containing all discovered domains and IP addresses.</span>
|
||||
</div>
|
||||
<button id="export-executive-summary" class="btn btn-primary" style="margin-top: 1rem;">
|
||||
<span class="btn-icon">[TXT]</span>
|
||||
<span>Export Executive Summary</span>
|
||||
</button>
|
||||
<div class="status-row" style="margin-top: 0.5rem;">
|
||||
<span class="status-label">A natural-language summary of the scan findings.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# DNScope-reduced/utils/__init__.py
|
||||
|
||||
"""
|
||||
Utility modules for DNScope.
|
||||
Contains helper functions, export management, and supporting utilities.
|
||||
"""
|
||||
|
||||
from .helpers import is_valid_target, _is_valid_domain, _is_valid_ip, get_ip_version, normalize_ip
|
||||
from .export_manager import export_manager, ExportManager, CustomJSONEncoder
|
||||
|
||||
__all__ = [
|
||||
'is_valid_target',
|
||||
'_is_valid_domain',
|
||||
'_is_valid_ip',
|
||||
'get_ip_version',
|
||||
'normalize_ip',
|
||||
'export_manager',
|
||||
'ExportManager',
|
||||
'CustomJSONEncoder'
|
||||
]
|
||||
|
||||
__version__ = "1.0.0"
|
||||
800
utils/export_manager.py
Normal file
800
utils/export_manager.py
Normal file
@@ -0,0 +1,800 @@
|
||||
# DNScope-reduced/utils/export_manager.py
|
||||
|
||||
"""
|
||||
Centralized export functionality for DNScope.
|
||||
Handles all data export operations with forensic integrity and proper formatting.
|
||||
ENHANCED: Professional forensic executive summary generation for court-ready documentation.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Any, List, Optional, Set, Tuple
|
||||
from decimal import Decimal
|
||||
from collections import defaultdict, Counter
|
||||
import networkx as nx
|
||||
|
||||
from utils.helpers import _is_valid_domain, _is_valid_ip
|
||||
|
||||
|
||||
class ExportManager:
|
||||
"""
|
||||
Centralized manager for all DNScope export operations.
|
||||
Maintains forensic integrity and provides consistent export formats.
|
||||
ENHANCED: Advanced forensic analysis and professional reporting capabilities.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize export manager."""
|
||||
pass
|
||||
|
||||
def export_scan_results(self, scanner) -> Dict[str, Any]:
|
||||
"""
|
||||
Export complete scan results with forensic metadata.
|
||||
|
||||
Args:
|
||||
scanner: Scanner instance with completed scan data
|
||||
|
||||
Returns:
|
||||
Complete scan results dictionary
|
||||
"""
|
||||
graph_data = self.export_graph_json(scanner.graph)
|
||||
audit_trail = scanner.logger.export_audit_trail()
|
||||
provider_stats = {}
|
||||
|
||||
for provider in scanner.providers:
|
||||
provider_stats[provider.get_name()] = provider.get_statistics()
|
||||
|
||||
results = {
|
||||
'scan_metadata': {
|
||||
'target_domain': scanner.current_target,
|
||||
'max_depth': scanner.max_depth,
|
||||
'final_status': scanner.status,
|
||||
'total_indicators_processed': scanner.indicators_processed,
|
||||
'enabled_providers': list(provider_stats.keys()),
|
||||
'session_id': scanner.session_id
|
||||
},
|
||||
'graph_data': graph_data,
|
||||
'forensic_audit': audit_trail,
|
||||
'provider_statistics': provider_stats,
|
||||
'scan_summary': scanner.logger.get_forensic_summary()
|
||||
}
|
||||
|
||||
# Add export metadata
|
||||
results['export_metadata'] = {
|
||||
'export_timestamp': datetime.now(timezone.utc).isoformat(),
|
||||
'export_version': '1.0.0',
|
||||
'forensic_integrity': 'maintained'
|
||||
}
|
||||
|
||||
return results
|
||||
|
||||
def export_targets_list(self, scanner) -> str:
|
||||
"""
|
||||
Export all discovered domains and IPs as a text file.
|
||||
|
||||
Args:
|
||||
scanner: Scanner instance with graph data
|
||||
|
||||
Returns:
|
||||
Newline-separated list of targets
|
||||
"""
|
||||
nodes = scanner.graph.get_graph_data().get('nodes', [])
|
||||
targets = {
|
||||
node['id'] for node in nodes
|
||||
if _is_valid_domain(node['id']) or _is_valid_ip(node['id'])
|
||||
}
|
||||
return "\n".join(sorted(list(targets)))
|
||||
|
||||
def generate_executive_summary(self, scanner) -> str:
|
||||
"""
|
||||
ENHANCED: Generate a comprehensive, court-ready forensic executive summary.
|
||||
|
||||
Args:
|
||||
scanner: Scanner instance with completed scan data
|
||||
|
||||
Returns:
|
||||
Professional forensic summary formatted for investigative use
|
||||
"""
|
||||
report = []
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
|
||||
|
||||
# Get comprehensive data for analysis
|
||||
graph_data = scanner.graph.get_graph_data()
|
||||
nodes = graph_data.get('nodes', [])
|
||||
edges = graph_data.get('edges', [])
|
||||
audit_trail = scanner.logger.export_audit_trail()
|
||||
|
||||
# Perform advanced analysis
|
||||
infrastructure_analysis = self._analyze_infrastructure_patterns(nodes, edges)
|
||||
|
||||
# === HEADER AND METADATA ===
|
||||
report.extend([
|
||||
"=" * 80,
|
||||
"DIGITAL INFRASTRUCTURE RECONNAISSANCE REPORT",
|
||||
"=" * 80,
|
||||
"",
|
||||
f"Report Generated: {now}",
|
||||
f"Investigation Target: {scanner.current_target}",
|
||||
f"Analysis Session: {scanner.session_id}",
|
||||
f"Scan Depth: {scanner.max_depth} levels",
|
||||
f"Final Status: {scanner.status.upper()}",
|
||||
""
|
||||
])
|
||||
|
||||
# === EXECUTIVE SUMMARY ===
|
||||
report.extend([
|
||||
"EXECUTIVE SUMMARY",
|
||||
"-" * 40,
|
||||
"",
|
||||
f"This report presents the findings of a comprehensive passive reconnaissance analysis "
|
||||
f"conducted against the target '{scanner.current_target}'. The investigation employed "
|
||||
f"multiple intelligence sources and discovered {len(nodes)} distinct digital entities "
|
||||
f"connected through {len(edges)} verified relationships.",
|
||||
"",
|
||||
f"The analysis reveals a digital infrastructure comprising {infrastructure_analysis['domains']} "
|
||||
f"domain names, {infrastructure_analysis['ips']} IP addresses, and {infrastructure_analysis['isps']} "
|
||||
f"infrastructure service providers. Certificate transparency analysis identified "
|
||||
f"{infrastructure_analysis['cas']} certificate authorities managing the cryptographic "
|
||||
f"infrastructure for the investigated entities.",
|
||||
"",
|
||||
])
|
||||
|
||||
# === METHODOLOGY ===
|
||||
report.extend([
|
||||
"INVESTIGATIVE METHODOLOGY",
|
||||
"-" * 40,
|
||||
"",
|
||||
"This analysis employed passive reconnaissance techniques using the following verified data sources:",
|
||||
""
|
||||
])
|
||||
|
||||
provider_info = {
|
||||
'dns': 'Standard DNS resolution and reverse DNS lookups',
|
||||
'crtsh': 'Certificate Transparency database analysis via crt.sh',
|
||||
'shodan': 'Internet-connected device intelligence via Shodan API'
|
||||
}
|
||||
|
||||
for provider in scanner.providers:
|
||||
provider_name = provider.get_name()
|
||||
stats = provider.get_statistics()
|
||||
description = provider_info.get(provider_name, f'{provider_name} data provider')
|
||||
|
||||
report.extend([
|
||||
f"• {provider.get_display_name()}: {description}",
|
||||
f" - Total Requests: {stats['total_requests']}",
|
||||
f" - Success Rate: {stats['success_rate']:.1f}%",
|
||||
f" - Relationships Discovered: {stats['relationships_found']}",
|
||||
""
|
||||
])
|
||||
|
||||
# === INFRASTRUCTURE ANALYSIS ===
|
||||
report.extend([
|
||||
"INFRASTRUCTURE ANALYSIS",
|
||||
"-" * 40,
|
||||
""
|
||||
])
|
||||
|
||||
# Domain Analysis
|
||||
if infrastructure_analysis['domains'] > 0:
|
||||
report.extend([
|
||||
f"Domain Name Infrastructure ({infrastructure_analysis['domains']} entities):",
|
||||
""
|
||||
])
|
||||
|
||||
domain_details = self._get_detailed_domain_analysis(nodes, edges)
|
||||
for domain_info in domain_details[:10]: # Top 10 domains
|
||||
report.extend([
|
||||
f"• {domain_info['domain']}",
|
||||
f" - Type: {domain_info['classification']}",
|
||||
f" - Connected IPs: {len(domain_info['ips'])}",
|
||||
f" - Certificate Status: {domain_info['cert_status']}",
|
||||
])
|
||||
|
||||
if domain_info['security_notes']:
|
||||
report.extend([
|
||||
f" - Security Notes: {', '.join(domain_info['security_notes'])}",
|
||||
])
|
||||
report.append("")
|
||||
|
||||
# IP Address Analysis
|
||||
if infrastructure_analysis['ips'] > 0:
|
||||
report.extend([
|
||||
f"IP Address Infrastructure ({infrastructure_analysis['ips']} entities):",
|
||||
""
|
||||
])
|
||||
|
||||
ip_details = self._get_detailed_ip_analysis(nodes, edges)
|
||||
for ip_info in ip_details[:8]: # Top 8 IPs
|
||||
report.extend([
|
||||
f"• {ip_info['ip']} ({ip_info['version']})",
|
||||
f" - Associated Domains: {len(ip_info['domains'])}",
|
||||
f" - ISP: {ip_info['isp'] or 'Unknown'}",
|
||||
f" - Geographic Location: {ip_info['location'] or 'Not determined'}",
|
||||
])
|
||||
|
||||
if ip_info['open_ports']:
|
||||
report.extend([
|
||||
f" - Exposed Services: {', '.join(map(str, ip_info['open_ports'][:5]))}"
|
||||
+ (f" (and {len(ip_info['open_ports']) - 5} more)" if len(ip_info['open_ports']) > 5 else ""),
|
||||
])
|
||||
report.append("")
|
||||
|
||||
# === RELATIONSHIP ANALYSIS ===
|
||||
report.extend([
|
||||
"ENTITY RELATIONSHIP ANALYSIS",
|
||||
"-" * 40,
|
||||
""
|
||||
])
|
||||
|
||||
# Network topology insights
|
||||
topology = self._analyze_network_topology(nodes, edges)
|
||||
report.extend([
|
||||
f"Network Topology Assessment:",
|
||||
f"• Central Hubs: {len(topology['hubs'])} entities serve as primary connection points",
|
||||
f"• Isolated Clusters: {len(topology['clusters'])} distinct groupings identified",
|
||||
f"• Relationship Density: {topology['density']:.3f} (0=sparse, 1=fully connected)",
|
||||
f"• Average Path Length: {topology['avg_path_length']:.2f} degrees of separation",
|
||||
""
|
||||
])
|
||||
|
||||
# Key relationships
|
||||
key_relationships = self._identify_key_relationships(edges)
|
||||
if key_relationships:
|
||||
report.extend([
|
||||
"Critical Infrastructure Relationships:",
|
||||
""
|
||||
])
|
||||
|
||||
for rel in key_relationships[:8]: # Top 8 relationships
|
||||
report.extend([
|
||||
f"• {rel['source']} → {rel['target']}",
|
||||
f" - Relationship: {self._humanize_relationship_type(rel['type'])}",
|
||||
f" - Discovery Method: {rel['provider']}",
|
||||
""
|
||||
])
|
||||
|
||||
# === CERTIFICATE ANALYSIS ===
|
||||
cert_analysis = self._analyze_certificate_infrastructure(nodes)
|
||||
if cert_analysis['total_certs'] > 0:
|
||||
report.extend([
|
||||
"CERTIFICATE INFRASTRUCTURE ANALYSIS",
|
||||
"-" * 40,
|
||||
"",
|
||||
f"Certificate Status Overview:",
|
||||
f"• Total Certificates Analyzed: {cert_analysis['total_certs']}",
|
||||
f"• Valid Certificates: {cert_analysis['valid']}",
|
||||
f"• Expired/Invalid: {cert_analysis['expired']}",
|
||||
f"• Certificate Authorities: {len(cert_analysis['cas'])}",
|
||||
""
|
||||
])
|
||||
|
||||
if cert_analysis['cas']:
|
||||
report.extend([
|
||||
"Certificate Authority Distribution:",
|
||||
""
|
||||
])
|
||||
for ca, count in cert_analysis['cas'].most_common(5):
|
||||
report.extend([
|
||||
f"• {ca}: {count} certificate(s)",
|
||||
])
|
||||
report.append("")
|
||||
|
||||
|
||||
# === TECHNICAL APPENDIX ===
|
||||
report.extend([
|
||||
"TECHNICAL APPENDIX",
|
||||
"-" * 40,
|
||||
"",
|
||||
"Data Quality Assessment:",
|
||||
f"• Total API Requests: {audit_trail.get('session_metadata', {}).get('total_requests', 0)}",
|
||||
f"• Data Providers Used: {len(audit_trail.get('session_metadata', {}).get('providers_used', []))}",
|
||||
])
|
||||
|
||||
correlation_provider = next((p for p in scanner.providers if p.get_name() == 'correlation'), None)
|
||||
correlation_count = len(correlation_provider.correlation_index) if correlation_provider else 0
|
||||
|
||||
report.extend([
|
||||
"",
|
||||
"Correlation Analysis:",
|
||||
f"• Entity Correlations Identified: {correlation_count}",
|
||||
f"• Cross-Reference Validation: {self._count_cross_validated_relationships(edges)} relationships verified by multiple sources",
|
||||
""
|
||||
])
|
||||
|
||||
# === CONCLUSION ===
|
||||
report.extend([
|
||||
"CONCLUSION",
|
||||
"-" * 40,
|
||||
"",
|
||||
self._generate_conclusion(scanner.current_target, infrastructure_analysis,
|
||||
len(edges)),
|
||||
"",
|
||||
"This analysis was conducted using passive reconnaissance techniques and represents "
|
||||
"the digital infrastructure observable through public data sources at the time of investigation. "
|
||||
"All findings are supported by verifiable technical evidence and documented through "
|
||||
"a complete audit trail maintained for forensic integrity.",
|
||||
"",
|
||||
f"Investigation completed: {now}",
|
||||
f"Report authenticated by: DNScope v{self._get_version()}",
|
||||
"",
|
||||
"=" * 80,
|
||||
"END OF REPORT",
|
||||
"=" * 80
|
||||
])
|
||||
|
||||
return "\n".join(report)
|
||||
|
||||
def _analyze_infrastructure_patterns(self, nodes: List[Dict], edges: List[Dict]) -> Dict[str, Any]:
|
||||
"""Analyze infrastructure patterns and classify entities."""
|
||||
analysis = {
|
||||
'domains': len([n for n in nodes if n['type'] == 'domain']),
|
||||
'ips': len([n for n in nodes if n['type'] == 'ip']),
|
||||
'isps': len([n for n in nodes if n['type'] == 'isp']),
|
||||
'cas': len([n for n in nodes if n['type'] == 'ca']),
|
||||
'correlations': len([n for n in nodes if n['type'] == 'correlation_object'])
|
||||
}
|
||||
return analysis
|
||||
|
||||
def _get_detailed_domain_analysis(self, nodes: List[Dict], edges: List[Dict]) -> List[Dict[str, Any]]:
|
||||
"""Generate detailed analysis for each domain."""
|
||||
domain_nodes = [n for n in nodes if n['type'] == 'domain']
|
||||
domain_analysis = []
|
||||
|
||||
for domain in domain_nodes:
|
||||
# Find connected IPs
|
||||
connected_ips = [e['to'] for e in edges
|
||||
if e['from'] == domain['id'] and _is_valid_ip(e['to'])]
|
||||
|
||||
# Determine classification
|
||||
classification = "Primary Domain"
|
||||
if domain['id'].startswith('www.'):
|
||||
classification = "Web Interface"
|
||||
elif any(subdomain in domain['id'] for subdomain in ['api.', 'mail.', 'smtp.']):
|
||||
classification = "Service Endpoint"
|
||||
elif domain['id'].count('.') > 1:
|
||||
classification = "Subdomain"
|
||||
|
||||
# Certificate status
|
||||
cert_status = self._determine_certificate_status(domain)
|
||||
|
||||
# Security notes
|
||||
security_notes = []
|
||||
if cert_status == "Expired/Invalid":
|
||||
security_notes.append("Certificate validation issues")
|
||||
if len(connected_ips) == 0:
|
||||
security_notes.append("No IP resolution found")
|
||||
if len(connected_ips) > 5:
|
||||
security_notes.append("Multiple IP endpoints")
|
||||
|
||||
domain_edges = [e for e in edges if e['from'] == domain['id']]
|
||||
|
||||
domain_analysis.append({
|
||||
'domain': domain['id'],
|
||||
'classification': classification,
|
||||
'ips': connected_ips,
|
||||
'cert_status': cert_status,
|
||||
'security_notes': security_notes,
|
||||
})
|
||||
|
||||
# Sort by number of connections (most connected first)
|
||||
return sorted(domain_analysis, key=lambda x: len(x['ips']), reverse=True)
|
||||
|
||||
def _get_detailed_ip_analysis(self, nodes: List[Dict], edges: List[Dict]) -> List[Dict[str, Any]]:
|
||||
"""Generate detailed analysis for each IP address."""
|
||||
ip_nodes = [n for n in nodes if n['type'] == 'ip']
|
||||
ip_analysis = []
|
||||
|
||||
for ip in ip_nodes:
|
||||
# Find connected domains
|
||||
connected_domains = [e['from'] for e in edges
|
||||
if e['to'] == ip['id'] and _is_valid_domain(e['from'])]
|
||||
|
||||
# Extract metadata from attributes
|
||||
ip_version = "IPv4"
|
||||
location = None
|
||||
isp = None
|
||||
open_ports = []
|
||||
|
||||
for attr in ip.get('attributes', []):
|
||||
if attr.get('name') == 'country':
|
||||
location = attr.get('value')
|
||||
elif attr.get('name') == 'org':
|
||||
isp = attr.get('value')
|
||||
elif attr.get('name') == 'shodan_open_port':
|
||||
open_ports.append(attr.get('value'))
|
||||
elif 'ipv6' in str(attr.get('metadata', {})).lower():
|
||||
ip_version = "IPv6"
|
||||
|
||||
# Find ISP from relationships
|
||||
if not isp:
|
||||
isp_edges = [e for e in edges if e['from'] == ip['id'] and e['label'].endswith('_isp')]
|
||||
isp = isp_edges[0]['to'] if isp_edges else None
|
||||
|
||||
ip_analysis.append({
|
||||
'ip': ip['id'],
|
||||
'version': ip_version,
|
||||
'domains': connected_domains,
|
||||
'isp': isp,
|
||||
'location': location,
|
||||
'open_ports': open_ports
|
||||
})
|
||||
|
||||
# Sort by number of connected domains
|
||||
return sorted(ip_analysis, key=lambda x: len(x['domains']), reverse=True)
|
||||
|
||||
def _analyze_network_topology(self, nodes: List[Dict], edges: List[Dict]) -> Dict[str, Any]:
|
||||
"""Analyze network topology and identify key structural patterns."""
|
||||
if not nodes or not edges:
|
||||
return {'hubs': [], 'clusters': [], 'density': 0, 'avg_path_length': 0}
|
||||
|
||||
# Create NetworkX graph
|
||||
G = nx.DiGraph()
|
||||
for node in nodes:
|
||||
G.add_node(node['id'])
|
||||
for edge in edges:
|
||||
G.add_edge(edge['from'], edge['to'])
|
||||
|
||||
# Convert to undirected for certain analyses
|
||||
G_undirected = G.to_undirected()
|
||||
|
||||
# Identify hubs (nodes with high degree centrality)
|
||||
centrality = nx.degree_centrality(G_undirected)
|
||||
hub_threshold = max(centrality.values()) * 0.7 if centrality else 0
|
||||
hubs = [node for node, cent in centrality.items() if cent >= hub_threshold]
|
||||
|
||||
# Find connected components (clusters)
|
||||
clusters = list(nx.connected_components(G_undirected))
|
||||
|
||||
# Calculate density
|
||||
density = nx.density(G_undirected)
|
||||
|
||||
# Calculate average path length (for largest component)
|
||||
if G_undirected.number_of_nodes() > 1:
|
||||
largest_cc = max(nx.connected_components(G_undirected), key=len)
|
||||
subgraph = G_undirected.subgraph(largest_cc)
|
||||
try:
|
||||
avg_path_length = nx.average_shortest_path_length(subgraph)
|
||||
except:
|
||||
avg_path_length = 0
|
||||
else:
|
||||
avg_path_length = 0
|
||||
|
||||
return {
|
||||
'hubs': hubs,
|
||||
'clusters': clusters,
|
||||
'density': density,
|
||||
'avg_path_length': avg_path_length
|
||||
}
|
||||
|
||||
def _identify_key_relationships(self, edges: List[Dict]) -> List[Dict[str, Any]]:
|
||||
"""Identify the most significant relationships in the infrastructure."""
|
||||
# Score relationships by type importance
|
||||
relationship_importance = {
|
||||
'dns_a_record': 0.9,
|
||||
'dns_aaaa_record': 0.9,
|
||||
'crtsh_cert_issuer': 0.8,
|
||||
'shodan_isp': 0.8,
|
||||
'crtsh_san_certificate': 0.7,
|
||||
'dns_mx_record': 0.7,
|
||||
'dns_ns_record': 0.7
|
||||
}
|
||||
|
||||
edges = []
|
||||
for edge in edges:
|
||||
type_weight = relationship_importance.get(edge.get('label', ''), 0.5)
|
||||
|
||||
edges.append({
|
||||
'source': edge['from'],
|
||||
'target': edge['to'],
|
||||
'type': edge.get('label', ''),
|
||||
'provider': edge.get('source_provider', ''),
|
||||
})
|
||||
|
||||
# Return top relationships by score
|
||||
return sorted(edges, key=lambda x: x['score'], reverse=True)
|
||||
|
||||
def _analyze_certificate_infrastructure(self, nodes: List[Dict]) -> Dict[str, Any]:
|
||||
"""Analyze certificate infrastructure across all domains."""
|
||||
domain_nodes = [n for n in nodes if n['type'] == 'domain']
|
||||
ca_nodes = [n for n in nodes if n['type'] == 'ca']
|
||||
|
||||
valid_certs = 0
|
||||
expired_certs = 0
|
||||
total_certs = 0
|
||||
cas = Counter()
|
||||
|
||||
for domain in domain_nodes:
|
||||
for attr in domain.get('attributes', []):
|
||||
if attr.get('name') == 'cert_is_currently_valid':
|
||||
total_certs += 1
|
||||
if attr.get('value') is True:
|
||||
valid_certs += 1
|
||||
else:
|
||||
expired_certs += 1
|
||||
elif attr.get('name') == 'cert_issuer_name':
|
||||
issuer = attr.get('value')
|
||||
if issuer:
|
||||
cas[issuer] += 1
|
||||
|
||||
return {
|
||||
'total_certs': total_certs,
|
||||
'valid': valid_certs,
|
||||
'expired': expired_certs,
|
||||
'cas': cas
|
||||
}
|
||||
|
||||
def _has_expired_certificates(self, domain_node: Dict) -> bool:
|
||||
"""Check if domain has expired certificates."""
|
||||
for attr in domain_node.get('attributes', []):
|
||||
if (attr.get('name') == 'cert_is_currently_valid' and
|
||||
attr.get('value') is False):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _determine_certificate_status(self, domain_node: Dict) -> str:
|
||||
"""Determine the certificate status for a domain."""
|
||||
has_valid = False
|
||||
has_expired = False
|
||||
has_any = False
|
||||
|
||||
for attr in domain_node.get('attributes', []):
|
||||
if attr.get('name') == 'cert_is_currently_valid':
|
||||
has_any = True
|
||||
if attr.get('value') is True:
|
||||
has_valid = True
|
||||
else:
|
||||
has_expired = True
|
||||
|
||||
if not has_any:
|
||||
return "No Certificate Data"
|
||||
elif has_valid and not has_expired:
|
||||
return "Valid"
|
||||
elif has_expired and not has_valid:
|
||||
return "Expired/Invalid"
|
||||
else:
|
||||
return "Mixed Status"
|
||||
|
||||
def _humanize_relationship_type(self, rel_type: str) -> str:
|
||||
"""Convert technical relationship types to human-readable descriptions."""
|
||||
type_map = {
|
||||
'dns_a_record': 'DNS A Record Resolution',
|
||||
'dns_aaaa_record': 'DNS AAAA Record (IPv6) Resolution',
|
||||
'dns_mx_record': 'Email Server (MX) Configuration',
|
||||
'dns_ns_record': 'Name Server Delegation',
|
||||
'dns_cname_record': 'DNS Alias (CNAME) Resolution',
|
||||
'crtsh_cert_issuer': 'SSL Certificate Issuer Relationship',
|
||||
'crtsh_san_certificate': 'Shared SSL Certificate',
|
||||
'shodan_isp': 'Internet Service Provider Assignment',
|
||||
'shodan_a_record': 'IP-to-Domain Resolution (Shodan)',
|
||||
'dns_ptr_record': 'Reverse DNS Resolution'
|
||||
}
|
||||
return type_map.get(rel_type, rel_type.replace('_', ' ').title())
|
||||
|
||||
def _count_cross_validated_relationships(self, edges: List[Dict]) -> int:
|
||||
"""Count relationships verified by multiple providers."""
|
||||
# Group edges by source-target pair
|
||||
edge_pairs = defaultdict(list)
|
||||
for edge in edges:
|
||||
pair_key = f"{edge['from']}->{edge['to']}"
|
||||
edge_pairs[pair_key].append(edge.get('source_provider', ''))
|
||||
|
||||
# Count pairs with multiple providers
|
||||
cross_validated = 0
|
||||
for pair, providers in edge_pairs.items():
|
||||
if len(set(providers)) > 1: # Multiple unique providers
|
||||
cross_validated += 1
|
||||
|
||||
return cross_validated
|
||||
|
||||
def _generate_security_recommendations(self, infrastructure_analysis: Dict) -> List[str]:
|
||||
"""Generate actionable security recommendations."""
|
||||
recommendations = []
|
||||
|
||||
# Check for complex infrastructure
|
||||
if infrastructure_analysis['ips'] > 10:
|
||||
recommendations.append(
|
||||
"Document and validate the necessity of extensive IP address infrastructure"
|
||||
)
|
||||
|
||||
if infrastructure_analysis['correlations'] > 5:
|
||||
recommendations.append(
|
||||
"Investigate shared infrastructure components for operational security implications"
|
||||
)
|
||||
|
||||
if not recommendations:
|
||||
recommendations.append(
|
||||
"Continue monitoring for changes in the identified digital infrastructure"
|
||||
)
|
||||
|
||||
return recommendations
|
||||
|
||||
def _generate_conclusion(self, target: str, infrastructure_analysis: Dict, total_relationships: int) -> str:
|
||||
"""Generate a professional conclusion for the report."""
|
||||
conclusion_parts = [
|
||||
f"The passive reconnaissance analysis of '{target}' has successfully mapped "
|
||||
f"a digital infrastructure ecosystem consisting of {infrastructure_analysis['domains']} "
|
||||
f"domain names, {infrastructure_analysis['ips']} IP addresses, and "
|
||||
f"{total_relationships} verified inter-entity relationships."
|
||||
]
|
||||
|
||||
conclusion_parts.append(
|
||||
"All findings in this report are based on publicly available information and "
|
||||
"passive reconnaissance techniques. The analysis maintains full forensic integrity "
|
||||
"with complete audit trails for all data collection activities."
|
||||
)
|
||||
|
||||
return " ".join(conclusion_parts)
|
||||
|
||||
def _count_bidirectional_relationships(self, graph) -> int:
|
||||
"""Count bidirectional relationships in the graph."""
|
||||
count = 0
|
||||
for u, v in graph.edges():
|
||||
if graph.has_edge(v, u):
|
||||
count += 1
|
||||
return count // 2 # Each pair counted twice
|
||||
|
||||
def _identify_hub_nodes(self, graph, nodes: List[Dict]) -> List[str]:
|
||||
"""Identify nodes that serve as major hubs in the network."""
|
||||
if not graph.nodes():
|
||||
return []
|
||||
|
||||
degree_centrality = nx.degree_centrality(graph.to_undirected())
|
||||
threshold = max(degree_centrality.values()) * 0.8 if degree_centrality else 0
|
||||
|
||||
return [node for node, centrality in degree_centrality.items()
|
||||
if centrality >= threshold]
|
||||
|
||||
def _get_version(self) -> str:
|
||||
"""Get DNScope version for report authentication."""
|
||||
return "1.0.0-forensic"
|
||||
|
||||
def export_graph_json(self, graph_manager) -> Dict[str, Any]:
|
||||
"""
|
||||
Export complete graph data as a JSON-serializable dictionary.
|
||||
Moved from GraphManager to centralize export functionality.
|
||||
|
||||
Args:
|
||||
graph_manager: GraphManager instance with graph data
|
||||
|
||||
Returns:
|
||||
Complete graph data with export metadata
|
||||
"""
|
||||
graph_data = nx.node_link_data(graph_manager.graph, edges="edges")
|
||||
|
||||
return {
|
||||
'export_metadata': {
|
||||
'export_timestamp': datetime.now(timezone.utc).isoformat(),
|
||||
'graph_creation_time': graph_manager.creation_time,
|
||||
'last_modified': graph_manager.last_modified,
|
||||
'total_nodes': graph_manager.get_node_count(),
|
||||
'total_edges': graph_manager.get_edge_count(),
|
||||
'graph_format': 'DNScope_v1_unified_model'
|
||||
},
|
||||
'graph': graph_data,
|
||||
'statistics': graph_manager.get_statistics()
|
||||
}
|
||||
|
||||
def serialize_to_json(self, data: Dict[str, Any], indent: int = 2) -> str:
|
||||
"""
|
||||
Serialize data to JSON with custom handling for non-serializable objects.
|
||||
|
||||
Args:
|
||||
data: Data to serialize
|
||||
indent: JSON indentation level
|
||||
|
||||
Returns:
|
||||
JSON string representation
|
||||
"""
|
||||
try:
|
||||
return json.dumps(data, indent=indent, cls=CustomJSONEncoder, ensure_ascii=False)
|
||||
except Exception:
|
||||
# Fallback to aggressive cleaning
|
||||
cleaned_data = self._clean_for_json(data)
|
||||
return json.dumps(cleaned_data, indent=indent, ensure_ascii=False)
|
||||
|
||||
def _clean_for_json(self, obj, max_depth: int = 10, current_depth: int = 0) -> Any:
|
||||
"""
|
||||
Recursively clean an object to make it JSON serializable.
|
||||
Handles circular references and problematic object types.
|
||||
|
||||
Args:
|
||||
obj: Object to clean
|
||||
max_depth: Maximum recursion depth
|
||||
current_depth: Current recursion depth
|
||||
|
||||
Returns:
|
||||
JSON-serializable object
|
||||
"""
|
||||
if current_depth > max_depth:
|
||||
return f"<max_depth_exceeded_{type(obj).__name__}>"
|
||||
|
||||
if obj is None or isinstance(obj, (bool, int, float, str)):
|
||||
return obj
|
||||
elif isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, (set, frozenset)):
|
||||
return list(obj)
|
||||
elif isinstance(obj, dict):
|
||||
cleaned = {}
|
||||
for key, value in obj.items():
|
||||
try:
|
||||
# Ensure key is string
|
||||
clean_key = str(key) if not isinstance(key, str) else key
|
||||
cleaned[clean_key] = self._clean_for_json(value, max_depth, current_depth + 1)
|
||||
except Exception:
|
||||
cleaned[str(key)] = f"<serialization_error_{type(value).__name__}>"
|
||||
return cleaned
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
cleaned = []
|
||||
for item in obj:
|
||||
try:
|
||||
cleaned.append(self._clean_for_json(item, max_depth, current_depth + 1))
|
||||
except Exception:
|
||||
cleaned.append(f"<serialization_error_{type(item).__name__}>")
|
||||
return cleaned
|
||||
elif hasattr(obj, '__dict__'):
|
||||
try:
|
||||
return self._clean_for_json(obj.__dict__, max_depth, current_depth + 1)
|
||||
except Exception:
|
||||
return str(obj)
|
||||
elif hasattr(obj, 'value'):
|
||||
# For enum-like objects
|
||||
return obj.value
|
||||
else:
|
||||
return str(obj)
|
||||
|
||||
def generate_filename(self, target: str, export_type: str, timestamp: Optional[datetime] = None) -> str:
|
||||
"""
|
||||
Generate standardized filename for exports.
|
||||
|
||||
Args:
|
||||
target: Target domain/IP being scanned
|
||||
export_type: Type of export (json, txt, summary)
|
||||
timestamp: Optional timestamp (defaults to now)
|
||||
|
||||
Returns:
|
||||
Formatted filename with forensic naming convention
|
||||
"""
|
||||
if timestamp is None:
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
|
||||
timestamp_str = timestamp.strftime('%Y%m%d_%H%M%S')
|
||||
safe_target = "".join(c for c in target if c.isalnum() or c in ('-', '_', '.')).rstrip()
|
||||
|
||||
extension_map = {
|
||||
'json': 'json',
|
||||
'txt': 'txt',
|
||||
'summary': 'txt',
|
||||
'targets': 'txt'
|
||||
}
|
||||
|
||||
extension = extension_map.get(export_type, 'txt')
|
||||
return f"DNScope_{export_type}_{safe_target}_{timestamp_str}.{extension}"
|
||||
|
||||
|
||||
class CustomJSONEncoder(json.JSONEncoder):
|
||||
"""Custom JSON encoder to handle non-serializable objects."""
|
||||
|
||||
def default(self, obj):
|
||||
if isinstance(obj, datetime):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, set):
|
||||
return list(obj)
|
||||
elif isinstance(obj, Decimal):
|
||||
return float(obj)
|
||||
elif hasattr(obj, '__dict__'):
|
||||
# For custom objects, try to serialize their dict representation
|
||||
try:
|
||||
return obj.__dict__
|
||||
except:
|
||||
return str(obj)
|
||||
elif hasattr(obj, 'value') and hasattr(obj, 'name'):
|
||||
# For enum objects
|
||||
return obj.value
|
||||
else:
|
||||
# For any other non-serializable object, convert to string
|
||||
return str(obj)
|
||||
|
||||
|
||||
# Global export manager instance
|
||||
export_manager = ExportManager()
|
||||
@@ -1,4 +1,4 @@
|
||||
# dnsrecon-reduced/utils/helpers.py
|
||||
# DNScope-reduced/utils/helpers.py
|
||||
|
||||
import ipaddress
|
||||
from typing import Union
|
||||
|
||||
Reference in New Issue
Block a user