Compare commits
28 Commits
database_c
...
main
Author | SHA1 | Date | |
---|---|---|---|
![]() |
0e92ec6e9a | ||
![]() |
baa57bfac2 | ||
![]() |
f0f80be955 | ||
![]() |
ecc143ddbb | ||
![]() |
2c48316477 | ||
![]() |
fc098aed28 | ||
9285226cbc | |||
![]() |
350055fcec | ||
![]() |
4a5ecf7a37 | ||
![]() |
71b2855d01 | ||
![]() |
93a258170a | ||
![]() |
e2d4e12057 | ||
![]() |
c076ee028f | ||
![]() |
cbfac0922a | ||
![]() |
881f7b74e5 | ||
![]() |
c347581a6c | ||
![]() |
30ee21f087 | ||
![]() |
2496ca26a5 | ||
![]() |
8aa3c4933e | ||
![]() |
fc326a66c8 | ||
![]() |
51902e3155 | ||
![]() |
a261d706c8 | ||
![]() |
2410e689b8 | ||
![]() |
62470673fe | ||
![]() |
2658bd148b | ||
![]() |
f02381910d | ||
![]() |
674ac59c98 | ||
434d1f4803 |
@ -29,6 +29,6 @@ MAX_CONCURRENT_REQUESTS=5
|
|||||||
# The number of results from a provider that triggers the "large entity" grouping.
|
# The number of results from a provider that triggers the "large entity" grouping.
|
||||||
LARGE_ENTITY_THRESHOLD=100
|
LARGE_ENTITY_THRESHOLD=100
|
||||||
# The number of times to retry a target if a provider fails.
|
# The number of times to retry a target if a provider fails.
|
||||||
MAX_RETRIES_PER_TARGET=3
|
MAX_RETRIES_PER_TARGET=8
|
||||||
# How long cached provider responses are stored (in hours).
|
# How long cached provider responses are stored (in hours).
|
||||||
CACHE_EXPIRY_HOURS=12
|
CACHE_EXPIRY_HOURS=12
|
||||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -169,3 +169,4 @@ cython_debug/
|
|||||||
#.idea/
|
#.idea/
|
||||||
|
|
||||||
dump.rdb
|
dump.rdb
|
||||||
|
cache/
|
226
README.md
226
README.md
@ -4,28 +4,32 @@ DNSRecon is an interactive, passive reconnaissance tool designed to map adversar
|
|||||||
|
|
||||||
**Current Status: Phase 2 Implementation**
|
**Current Status: Phase 2 Implementation**
|
||||||
|
|
||||||
- ✅ Core infrastructure and graph engine
|
* ✅ Core infrastructure and graph engine
|
||||||
- ✅ Multi-provider support (crt.sh, DNS, Shodan)
|
* ✅ Multi-provider support (crt.sh, DNS, Shodan)
|
||||||
- ✅ Session-based multi-user support
|
* ✅ Session-based multi-user support
|
||||||
- ✅ Real-time web interface with interactive visualization
|
* ✅ Real-time web interface with interactive visualization
|
||||||
- ✅ Forensic logging system and JSON export
|
* ✅ Forensic logging system and JSON export
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Passive Reconnaissance**: Gathers data without direct contact with target infrastructure.
|
* **Passive Reconnaissance**: Gathers data without direct contact with target infrastructure.
|
||||||
- **In-Memory Graph Analysis**: Uses NetworkX for efficient relationship mapping.
|
* **In-Memory Graph Analysis**: Uses NetworkX for efficient relationship mapping.
|
||||||
- **Real-Time Visualization**: The graph updates dynamically as the scan progresses.
|
* **Real-Time Visualization**: The graph updates dynamically as the scan progresses.
|
||||||
- **Forensic Logging**: A complete audit trail of all reconnaissance activities is maintained.
|
* **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.
|
* **Confidence Scoring**: Relationships are weighted based on the reliability of the data source.
|
||||||
- **Session Management**: Supports concurrent user sessions with isolated scanner instances.
|
* **Session Management**: Supports concurrent user sessions with isolated scanner instances.
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
- Python 3.8 or higher
|
* Python 3.8 or higher
|
||||||
- A modern web browser with JavaScript enabled
|
* A modern web browser with JavaScript enabled
|
||||||
- (Recommended) A Linux host for running the application and the optional DNS cache.
|
* (Recommended) A Linux host for running the application and the optional DNS cache.
|
||||||
|
|
||||||
### 1\. Clone the Project
|
### 1\. Clone the Project
|
||||||
|
|
||||||
@ -44,156 +48,50 @@ source venv/bin/activate
|
|||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3\. (Optional but Recommended) Set up a Local DNS Caching Resolver
|
The `requirements.txt` file contains the following dependencies:
|
||||||
|
|
||||||
Running a local DNS caching resolver can significantly speed up DNS queries and reduce your network footprint. Here’s how to set up `unbound` on a Debian-based Linux distribution (like Ubuntu).
|
* 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
|
||||||
|
* gunicorn
|
||||||
|
* redis
|
||||||
|
* python-dotenv
|
||||||
|
|
||||||
**a. Install Unbound:**
|
-----
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
DNSRecon is configured using a `.env` file. You can copy the provided example file and edit it to suit your needs:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt update
|
cp .env.example .env
|
||||||
sudo apt install unbound -y
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**b. Configure Unbound:**
|
The following environment variables are available for configuration:
|
||||||
Create a new configuration file for DNSRecon:
|
|
||||||
|
|
||||||
```bash
|
| Variable | Description | Default |
|
||||||
sudo nano /etc/unbound/unbound.conf.d/dnsrecon.conf
|
| :--- | :--- | :--- |
|
||||||
```
|
| `SHODAN_API_KEY` | Your Shodan API key. | |
|
||||||
|
| `FLASK_SECRET_KEY`| A strong, random secret key for session security. | `your-very-secret-and-random-key-here` |
|
||||||
|
| `FLASK_HOST` | The host address for the Flask application. | `127.0.0.1` |
|
||||||
|
| `FLASK_PORT` | The port for the Flask application. | `5000` |
|
||||||
|
| `FLASK_DEBUG` | Enable or disable Flask's debug mode. | `True` |
|
||||||
|
| `FLASK_PERMANENT_SESSION_LIFETIME_HOURS`| How long a user's session in the browser lasts (in hours). | `2` |
|
||||||
|
| `SESSION_TIMEOUT_MINUTES` | How long inactive scanner data is stored in Redis (in minutes). | `60` |
|
||||||
|
| `DEFAULT_RECURSION_DEPTH` | The default number of levels to recurse when scanning. | `2` |
|
||||||
|
| `DEFAULT_TIMEOUT` | Default timeout for provider API requests in seconds. | `30` |
|
||||||
|
| `MAX_CONCURRENT_REQUESTS`| The number of concurrent provider requests to make. | `5` |
|
||||||
|
| `LARGE_ENTITY_THRESHOLD`| The number of results from a provider that triggers the "large entity" grouping. | `100` |
|
||||||
|
| `MAX_RETRIES_PER_TARGET`| The number of times to retry a target if a provider fails. | `8` |
|
||||||
|
| `CACHE_EXPIRY_HOURS`| How long cached provider responses are stored (in hours). | `12` |
|
||||||
|
|
||||||
Add the following content to the file:
|
-----
|
||||||
|
|
||||||
```
|
## Systemd Service
|
||||||
server:
|
|
||||||
# Listen on localhost for all users
|
|
||||||
interface: 127.0.0.1
|
|
||||||
access-control: 0.0.0.0/0 refuse
|
|
||||||
access-control: 127.0.0.0/8 allow
|
|
||||||
|
|
||||||
# Enable prefetching of popular items
|
|
||||||
prefetch: yes
|
|
||||||
```
|
|
||||||
|
|
||||||
**c. Restart Unbound and set it as the default resolver:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo systemctl restart unbound
|
|
||||||
sudo systemctl enable unbound
|
|
||||||
```
|
|
||||||
|
|
||||||
To use this resolver for your system, you may need to update your network settings to point to `127.0.0.1` as your DNS server.
|
|
||||||
|
|
||||||
**d. Update DNSProvider to use the local resolver:**
|
|
||||||
In `dnsrecon/providers/dns_provider.py`, you can explicitly set the resolver's nameservers in the `__init__` method:
|
|
||||||
|
|
||||||
```python
|
|
||||||
# dnsrecon/providers/dns_provider.py
|
|
||||||
|
|
||||||
class DNSProvider(BaseProvider):
|
|
||||||
def __init__(self, session_config=None):
|
|
||||||
"""Initialize DNS provider with session-specific configuration."""
|
|
||||||
super().__init__(...)
|
|
||||||
|
|
||||||
# Configure DNS resolver
|
|
||||||
self.resolver = dns.resolver.Resolver()
|
|
||||||
self.resolver.nameservers = ['127.0.0.1'] # Use local caching resolver
|
|
||||||
self.resolver.timeout = 5
|
|
||||||
self.resolver.lifetime = 10
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage (Development)
|
|
||||||
|
|
||||||
### 1\. Start the Application
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python app.py
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2\. Open Your Browser
|
|
||||||
|
|
||||||
Navigate to `http://127.0.0.1:5000`.
|
|
||||||
|
|
||||||
### 3\. Basic Reconnaissance Workflow
|
|
||||||
|
|
||||||
1. **Enter Target Domain**: Input a domain like `example.com`.
|
|
||||||
2. **Select Recursion Depth**: Depth 2 is recommended for most investigations.
|
|
||||||
3. **Start Reconnaissance**: Click "Start Reconnaissance" to begin.
|
|
||||||
4. **Monitor Progress**: Watch the real-time graph build as relationships are discovered.
|
|
||||||
5. **Analyze and Export**: Interact with the graph and download the results when the scan is complete.
|
|
||||||
|
|
||||||
## Production Deployment
|
|
||||||
|
|
||||||
To deploy DNSRecon in a production environment, follow these steps:
|
|
||||||
|
|
||||||
### 1\. Use a Production WSGI Server
|
|
||||||
|
|
||||||
Do not use the built-in Flask development server for production. Use a WSGI server like **Gunicorn**:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install gunicorn
|
|
||||||
gunicorn --workers 4 --bind 0.0.0.0:5000 app:app
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2\. Configure Environment Variables
|
|
||||||
|
|
||||||
Set the following environment variables for a secure and configurable deployment:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate a strong, random secret key
|
|
||||||
export SECRET_KEY='your-super-secret-and-random-key'
|
|
||||||
|
|
||||||
# Set Flask to production mode
|
|
||||||
export FLASK_ENV='production'
|
|
||||||
export FLASK_DEBUG=False
|
|
||||||
|
|
||||||
# API keys (optional, but recommended for full functionality)
|
|
||||||
export SHODAN_API_KEY="your_shodan_key"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3\. Use a Reverse Proxy
|
|
||||||
|
|
||||||
Set up a reverse proxy like **Nginx** to sit in front of the Gunicorn server. This provides several benefits, including:
|
|
||||||
|
|
||||||
- **TLS/SSL Termination**: Securely handle HTTPS traffic.
|
|
||||||
- **Load Balancing**: Distribute traffic across multiple application instances.
|
|
||||||
- **Serving Static Files**: Efficiently serve CSS and JavaScript files.
|
|
||||||
|
|
||||||
**Example Nginx Configuration:**
|
|
||||||
|
|
||||||
```nginx
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
server_name your_domain.com;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
return 301 https://$host$request_uri;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
server {
|
|
||||||
listen 443 ssl;
|
|
||||||
server_name your_domain.com;
|
|
||||||
|
|
||||||
# SSL cert configuration
|
|
||||||
ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
|
|
||||||
ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://127.0.0.1:5000;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
}
|
|
||||||
|
|
||||||
location /static {
|
|
||||||
alias /path/to/your/dnsrecon/static;
|
|
||||||
expires 30d;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Autostart with systemd
|
|
||||||
|
|
||||||
To run DNSRecon as a service that starts automatically on boot, you can use `systemd`.
|
To run DNSRecon as a service that starts automatically on boot, you can use `systemd`.
|
||||||
|
|
||||||
@ -245,12 +143,18 @@ You can check the status of the service at any time with:
|
|||||||
sudo systemctl status dnsrecon.service
|
sudo systemctl status dnsrecon.service
|
||||||
```
|
```
|
||||||
|
|
||||||
## Security Considerations
|
-----
|
||||||
|
|
||||||
- **API Keys**: API keys are stored in memory for the duration of a user session and are not written to disk.
|
|
||||||
- **Rate Limiting**: DNSRecon includes built-in rate limiting to be respectful to data sources.
|
|
||||||
- **Local Use**: The application is designed for local or trusted network use and does not have built-in authentication. **Do not expose it directly to the internet without proper security controls.**
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the terms of the license agreement found in the `LICENSE` file.
|
This project is licensed under the terms of the **BSD-3-Clause** license.
|
||||||
|
|
||||||
|
Copyright (c) 2025 mstoeck3.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||||
|
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
126
app.py
126
app.py
@ -13,6 +13,8 @@ import io
|
|||||||
|
|
||||||
from core.session_manager import session_manager
|
from core.session_manager import session_manager
|
||||||
from config import config
|
from config import config
|
||||||
|
from core.graph_manager import NodeType
|
||||||
|
from utils.helpers import is_valid_target
|
||||||
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
@ -64,18 +66,21 @@ def start_scan():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
if not data or 'target_domain' not in data:
|
if not data or 'target' not in data:
|
||||||
return jsonify({'success': False, 'error': 'Missing target_domain in request'}), 400
|
return jsonify({'success': False, 'error': 'Missing target in request'}), 400
|
||||||
|
|
||||||
target_domain = data['target_domain'].strip()
|
target = data['target'].strip()
|
||||||
max_depth = data.get('max_depth', config.default_recursion_depth)
|
max_depth = data.get('max_depth', config.default_recursion_depth)
|
||||||
clear_graph = data.get('clear_graph', True)
|
clear_graph = data.get('clear_graph', True)
|
||||||
|
force_rescan_target = data.get('force_rescan_target', None) # **FIX**: Get the new parameter
|
||||||
|
|
||||||
print(f"Parsed - target_domain: '{target_domain}', max_depth: {max_depth}, clear_graph: {clear_graph}")
|
print(f"Parsed - target: '{target}', max_depth: {max_depth}, clear_graph: {clear_graph}, force_rescan: {force_rescan_target}")
|
||||||
|
|
||||||
# Validation
|
# Validation
|
||||||
if not target_domain:
|
if not target:
|
||||||
return jsonify({'success': False, 'error': 'Target domain cannot be empty'}), 400
|
return jsonify({'success': False, 'error': 'Target cannot be empty'}), 400
|
||||||
|
if not is_valid_target(target):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid target format. Please enter a valid domain or IP address.'}), 400
|
||||||
if not isinstance(max_depth, int) or not 1 <= max_depth <= 5:
|
if not isinstance(max_depth, int) or not 1 <= max_depth <= 5:
|
||||||
return jsonify({'success': False, 'error': 'Max depth must be an integer between 1 and 5'}), 400
|
return jsonify({'success': False, 'error': 'Max depth must be an integer between 1 and 5'}), 400
|
||||||
|
|
||||||
@ -100,7 +105,7 @@ def start_scan():
|
|||||||
|
|
||||||
print(f"Using scanner {id(scanner)} in session {user_session_id}")
|
print(f"Using scanner {id(scanner)} in session {user_session_id}")
|
||||||
|
|
||||||
success = scanner.start_scan(target_domain, max_depth, clear_graph=clear_graph)
|
success = scanner.start_scan(target, max_depth, clear_graph=clear_graph, force_rescan_target=force_rescan_target) # **FIX**: Pass the new parameter
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@ -277,6 +282,108 @@ def get_graph_data():
|
|||||||
}
|
}
|
||||||
}), 500
|
}), 500
|
||||||
|
|
||||||
|
@app.route('/api/graph/large-entity/extract', methods=['POST'])
|
||||||
|
def extract_from_large_entity():
|
||||||
|
"""Extract a node from a large entity, making it a standalone node."""
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
large_entity_id = data.get('large_entity_id')
|
||||||
|
node_id = data.get('node_id')
|
||||||
|
|
||||||
|
if not large_entity_id or not node_id:
|
||||||
|
return jsonify({'success': False, 'error': 'Missing required parameters'}), 400
|
||||||
|
|
||||||
|
user_session_id, scanner = get_user_scanner()
|
||||||
|
if not scanner:
|
||||||
|
return jsonify({'success': False, 'error': 'No active session found'}), 404
|
||||||
|
|
||||||
|
success = scanner.extract_node_from_large_entity(large_entity_id, node_id)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
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
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ERROR: Exception in extract_from_large_entity endpoint: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return jsonify({'success': False, 'error': f'Internal server error: {str(e)}'}), 500
|
||||||
|
|
||||||
|
@app.route('/api/graph/node/<node_id>', methods=['DELETE'])
|
||||||
|
def delete_graph_node(node_id):
|
||||||
|
"""Delete a node from the graph for the current user session."""
|
||||||
|
try:
|
||||||
|
user_session_id, scanner = get_user_scanner()
|
||||||
|
if not scanner:
|
||||||
|
return jsonify({'success': False, 'error': 'No active session found'}), 404
|
||||||
|
|
||||||
|
success = scanner.graph.remove_node(node_id)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
# Persist the change
|
||||||
|
session_manager.update_session_scanner(user_session_id, scanner)
|
||||||
|
return jsonify({'success': True, 'message': f'Node {node_id} deleted successfully.'})
|
||||||
|
else:
|
||||||
|
return jsonify({'success': False, 'error': f'Node {node_id} not found in graph.'}), 404
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ERROR: Exception in delete_graph_node endpoint: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return jsonify({'success': False, 'error': f'Internal server error: {str(e)}'}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/graph/revert', methods=['POST'])
|
||||||
|
def revert_graph_action():
|
||||||
|
"""Reverts a graph action, such as re-adding a deleted node."""
|
||||||
|
try:
|
||||||
|
data = request.get_json()
|
||||||
|
if not data or 'type' not in data or 'data' not in data:
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid revert request format'}), 400
|
||||||
|
|
||||||
|
user_session_id, scanner = get_user_scanner()
|
||||||
|
if not scanner:
|
||||||
|
return jsonify({'success': False, 'error': 'No active session found'}), 404
|
||||||
|
|
||||||
|
action_type = data['type']
|
||||||
|
action_data = data['data']
|
||||||
|
|
||||||
|
if action_type == 'delete':
|
||||||
|
# Re-add the node
|
||||||
|
node_to_add = action_data.get('node')
|
||||||
|
if node_to_add:
|
||||||
|
scanner.graph.add_node(
|
||||||
|
node_id=node_to_add['id'],
|
||||||
|
node_type=NodeType(node_to_add['type']),
|
||||||
|
attributes=node_to_add.get('attributes'),
|
||||||
|
description=node_to_add.get('description'),
|
||||||
|
metadata=node_to_add.get('metadata')
|
||||||
|
)
|
||||||
|
|
||||||
|
# Re-add the edges
|
||||||
|
edges_to_add = action_data.get('edges', [])
|
||||||
|
for edge in edges_to_add:
|
||||||
|
# Add edge only if both nodes exist to prevent errors
|
||||||
|
if scanner.graph.graph.has_node(edge['from']) and scanner.graph.graph.has_node(edge['to']):
|
||||||
|
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', {})
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist the change
|
||||||
|
session_manager.update_session_scanner(user_session_id, scanner)
|
||||||
|
return jsonify({'success': True, 'message': 'Delete action reverted successfully.'})
|
||||||
|
|
||||||
|
return jsonify({'success': False, 'error': f'Unknown revert action type: {action_type}'}), 400
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ERROR: Exception in revert_graph_action endpoint: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return jsonify({'success': False, 'error': f'Internal server error: {str(e)}'}), 500
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/export', methods=['GET'])
|
@app.route('/api/export', methods=['GET'])
|
||||||
@ -330,9 +437,10 @@ def get_providers():
|
|||||||
user_session_id, scanner = get_user_scanner()
|
user_session_id, scanner = get_user_scanner()
|
||||||
|
|
||||||
if scanner:
|
if scanner:
|
||||||
|
# Updated debug print to be consistent with the new progress bar logic
|
||||||
completed_tasks = scanner.indicators_completed
|
completed_tasks = scanner.indicators_completed
|
||||||
enqueued_tasks = len(scanner.task_queue)
|
total_tasks = scanner.total_tasks_ever_enqueued
|
||||||
print(f"DEBUG: Tasks - Completed: {completed_tasks}, Enqueued: {enqueued_tasks}")
|
print(f"DEBUG: Task Progress - Completed: {completed_tasks}, Total Enqueued: {total_tasks}")
|
||||||
else:
|
else:
|
||||||
print("DEBUG: No active scanner session found.")
|
print("DEBUG: No active scanner session found.")
|
||||||
|
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
# dnsrecon-reduced/config.py
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Configuration management for DNSRecon tool.
|
Configuration management for DNSRecon tool.
|
||||||
Handles API key storage, rate limiting, and default settings.
|
Handles API key storage, rate limiting, and default settings.
|
||||||
@ -19,10 +21,10 @@ class Config:
|
|||||||
|
|
||||||
# --- General Settings ---
|
# --- General Settings ---
|
||||||
self.default_recursion_depth = 2
|
self.default_recursion_depth = 2
|
||||||
self.default_timeout = 15
|
self.default_timeout = 30
|
||||||
self.max_concurrent_requests = 5
|
self.max_concurrent_requests = 5
|
||||||
self.large_entity_threshold = 100
|
self.large_entity_threshold = 100
|
||||||
self.max_retries_per_target = 3
|
self.max_retries_per_target = 8
|
||||||
self.cache_expiry_hours = 12
|
self.cache_expiry_hours = 12
|
||||||
|
|
||||||
# --- Provider Caching Settings ---
|
# --- Provider Caching Settings ---
|
||||||
@ -30,7 +32,7 @@ class Config:
|
|||||||
|
|
||||||
# --- Rate Limiting (requests per minute) ---
|
# --- Rate Limiting (requests per minute) ---
|
||||||
self.rate_limits = {
|
self.rate_limits = {
|
||||||
'crtsh': 30,
|
'crtsh': 5,
|
||||||
'shodan': 60,
|
'shodan': 60,
|
||||||
'dns': 100
|
'dns': 100
|
||||||
}
|
}
|
||||||
|
@ -414,6 +414,53 @@ class GraphManager:
|
|||||||
self.last_modified = datetime.now(timezone.utc).isoformat()
|
self.last_modified = datetime.now(timezone.utc).isoformat()
|
||||||
return True
|
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', {})
|
||||||
|
|
||||||
|
# Remove from the list of member nodes
|
||||||
|
if 'nodes' in attributes and node_id_to_extract in attributes['nodes']:
|
||||||
|
attributes['nodes'].remove(node_id_to_extract)
|
||||||
|
# Update the count
|
||||||
|
attributes['count'] = len(attributes['nodes'])
|
||||||
|
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):
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 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, nodes in self.correlation_index.items():
|
||||||
|
if node_id in nodes:
|
||||||
|
del nodes[node_id]
|
||||||
|
if not nodes: # If no other nodes are associated with this value, remove it
|
||||||
|
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
|
||||||
|
|
||||||
def get_node_count(self) -> int:
|
def get_node_count(self) -> int:
|
||||||
"""Get total number of nodes in the graph."""
|
"""Get total number of nodes in the graph."""
|
||||||
return self.graph.number_of_nodes()
|
return self.graph.number_of_nodes()
|
||||||
|
@ -50,7 +50,7 @@ class ForensicLogger:
|
|||||||
session_id: Unique identifier for this reconnaissance session
|
session_id: Unique identifier for this reconnaissance session
|
||||||
"""
|
"""
|
||||||
self.session_id = session_id or self._generate_session_id()
|
self.session_id = session_id or self._generate_session_id()
|
||||||
#self.lock = threading.Lock()
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
# Initialize audit trail storage
|
# Initialize audit trail storage
|
||||||
self.api_requests: List[APIRequest] = []
|
self.api_requests: List[APIRequest] = []
|
||||||
@ -86,6 +86,8 @@ class ForensicLogger:
|
|||||||
# Remove the unpickleable 'logger' attribute
|
# Remove the unpickleable 'logger' attribute
|
||||||
if 'logger' in state:
|
if 'logger' in state:
|
||||||
del state['logger']
|
del state['logger']
|
||||||
|
if 'lock' in state:
|
||||||
|
del state['lock']
|
||||||
return state
|
return state
|
||||||
|
|
||||||
def __setstate__(self, state):
|
def __setstate__(self, state):
|
||||||
@ -101,6 +103,7 @@ class ForensicLogger:
|
|||||||
console_handler = logging.StreamHandler()
|
console_handler = logging.StreamHandler()
|
||||||
console_handler.setFormatter(formatter)
|
console_handler.setFormatter(formatter)
|
||||||
self.logger.addHandler(console_handler)
|
self.logger.addHandler(console_handler)
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
def _generate_session_id(self) -> str:
|
def _generate_session_id(self) -> str:
|
||||||
"""Generate unique session identifier."""
|
"""Generate unique session identifier."""
|
||||||
|
29
core/rate_limiter.py
Normal file
29
core/rate_limiter.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
# dnsrecon-reduced/core/rate_limiter.py
|
||||||
|
|
||||||
|
import time
|
||||||
|
import redis
|
||||||
|
|
||||||
|
class GlobalRateLimiter:
|
||||||
|
def __init__(self, redis_client):
|
||||||
|
self.redis = redis_client
|
||||||
|
|
||||||
|
def is_rate_limited(self, key, limit, period):
|
||||||
|
"""
|
||||||
|
Check if a key is rate-limited.
|
||||||
|
"""
|
||||||
|
now = time.time()
|
||||||
|
key = f"rate_limit:{key}"
|
||||||
|
|
||||||
|
# Remove old timestamps
|
||||||
|
self.redis.zremrangebyscore(key, 0, now - period)
|
||||||
|
|
||||||
|
# Check the count
|
||||||
|
count = self.redis.zcard(key)
|
||||||
|
if count >= limit:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Add new timestamp
|
||||||
|
self.redis.zadd(key, {now: now})
|
||||||
|
self.redis.expire(key, period)
|
||||||
|
|
||||||
|
return False
|
300
core/scanner.py
300
core/scanner.py
@ -1,20 +1,22 @@
|
|||||||
# dnsrecon/core/scanner.py
|
# dnsrecon-reduced/core/scanner.py
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
import importlib
|
import importlib
|
||||||
|
import redis
|
||||||
from typing import List, Set, Dict, Any, Tuple, Optional
|
from typing import List, Set, Dict, Any, Tuple, Optional
|
||||||
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError, Future
|
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError, Future
|
||||||
from collections import defaultdict, deque
|
from collections import defaultdict
|
||||||
|
from queue import PriorityQueue
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from core.graph_manager import GraphManager, NodeType
|
from core.graph_manager import GraphManager, NodeType
|
||||||
from core.logger import get_forensic_logger, new_session
|
from core.logger import get_forensic_logger, new_session
|
||||||
from utils.helpers import _is_valid_ip, _is_valid_domain
|
from utils.helpers import _is_valid_ip, _is_valid_domain
|
||||||
from providers.base_provider import BaseProvider
|
from providers.base_provider import BaseProvider
|
||||||
|
from core.rate_limiter import GlobalRateLimiter
|
||||||
|
|
||||||
class ScanStatus:
|
class ScanStatus:
|
||||||
"""Enumeration of scan statuses."""
|
"""Enumeration of scan statuses."""
|
||||||
@ -50,7 +52,7 @@ class Scanner:
|
|||||||
self.stop_event = threading.Event()
|
self.stop_event = threading.Event()
|
||||||
self.scan_thread = None
|
self.scan_thread = None
|
||||||
self.session_id: Optional[str] = None # Will be set by session manager
|
self.session_id: Optional[str] = None # Will be set by session manager
|
||||||
self.task_queue = deque([])
|
self.task_queue = PriorityQueue()
|
||||||
self.target_retries = defaultdict(int)
|
self.target_retries = defaultdict(int)
|
||||||
self.scan_failed_due_to_retries = False
|
self.scan_failed_due_to_retries = False
|
||||||
|
|
||||||
@ -63,6 +65,7 @@ class Scanner:
|
|||||||
self.indicators_processed = 0
|
self.indicators_processed = 0
|
||||||
self.indicators_completed = 0
|
self.indicators_completed = 0
|
||||||
self.tasks_re_enqueued = 0
|
self.tasks_re_enqueued = 0
|
||||||
|
self.total_tasks_ever_enqueued = 0
|
||||||
self.current_indicator = ""
|
self.current_indicator = ""
|
||||||
|
|
||||||
# Concurrent processing configuration
|
# Concurrent processing configuration
|
||||||
@ -77,6 +80,9 @@ class Scanner:
|
|||||||
print("Initializing forensic logger...")
|
print("Initializing forensic logger...")
|
||||||
self.logger = get_forensic_logger()
|
self.logger = get_forensic_logger()
|
||||||
|
|
||||||
|
# Initialize global rate limiter
|
||||||
|
self.rate_limiter = GlobalRateLimiter(redis.StrictRedis(db=0))
|
||||||
|
|
||||||
print("Scanner initialization complete")
|
print("Scanner initialization complete")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -129,7 +135,10 @@ class Scanner:
|
|||||||
'stop_event',
|
'stop_event',
|
||||||
'scan_thread',
|
'scan_thread',
|
||||||
'executor',
|
'executor',
|
||||||
'processing_lock' # **NEW**: Exclude the processing lock
|
'processing_lock',
|
||||||
|
'task_queue',
|
||||||
|
'rate_limiter',
|
||||||
|
'logger'
|
||||||
]
|
]
|
||||||
|
|
||||||
for attr in unpicklable_attrs:
|
for attr in unpicklable_attrs:
|
||||||
@ -138,7 +147,6 @@ class Scanner:
|
|||||||
|
|
||||||
# Handle providers separately to ensure they're picklable
|
# Handle providers separately to ensure they're picklable
|
||||||
if 'providers' in state:
|
if 'providers' in state:
|
||||||
# The providers should be picklable now, but let's ensure clean state
|
|
||||||
for provider in state['providers']:
|
for provider in state['providers']:
|
||||||
if hasattr(provider, '_stop_event'):
|
if hasattr(provider, '_stop_event'):
|
||||||
provider._stop_event = None
|
provider._stop_event = None
|
||||||
@ -153,9 +161,15 @@ class Scanner:
|
|||||||
self.stop_event = threading.Event()
|
self.stop_event = threading.Event()
|
||||||
self.scan_thread = None
|
self.scan_thread = None
|
||||||
self.executor = None
|
self.executor = None
|
||||||
self.processing_lock = threading.Lock() # **NEW**: Recreate processing lock
|
self.processing_lock = threading.Lock()
|
||||||
|
self.task_queue = PriorityQueue()
|
||||||
|
self.rate_limiter = GlobalRateLimiter(redis.StrictRedis(db=0))
|
||||||
|
self.logger = get_forensic_logger()
|
||||||
|
|
||||||
|
if not hasattr(self, 'providers') or not self.providers:
|
||||||
|
print("Providers not found after loading session, re-initializing...")
|
||||||
|
self._initialize_providers()
|
||||||
|
|
||||||
# **NEW**: Reset processing tracking
|
|
||||||
if not hasattr(self, 'currently_processing'):
|
if not hasattr(self, 'currently_processing'):
|
||||||
self.currently_processing = set()
|
self.currently_processing = set()
|
||||||
|
|
||||||
@ -204,11 +218,12 @@ class Scanner:
|
|||||||
self._initialize_providers()
|
self._initialize_providers()
|
||||||
print("Session configuration updated")
|
print("Session configuration updated")
|
||||||
|
|
||||||
def start_scan(self, target_domain: str, max_depth: int = 2, clear_graph: bool = True) -> bool:
|
def start_scan(self, target: str, max_depth: int = 2, clear_graph: bool = True, force_rescan_target: Optional[str] = None) -> bool:
|
||||||
"""Start a new reconnaissance scan with proper cleanup of previous scans."""
|
"""Start a new reconnaissance scan with proper cleanup of previous scans."""
|
||||||
print(f"=== STARTING SCAN IN SCANNER {id(self)} ===")
|
print(f"=== STARTING SCAN IN SCANNER {id(self)} ===")
|
||||||
print(f"Session ID: {self.session_id}")
|
print(f"Session ID: {self.session_id}")
|
||||||
print(f"Initial scanner status: {self.status}")
|
print(f"Initial scanner status: {self.status}")
|
||||||
|
self.total_tasks_ever_enqueued = 0
|
||||||
|
|
||||||
# **IMPROVED**: More aggressive cleanup of previous scan
|
# **IMPROVED**: More aggressive cleanup of previous scan
|
||||||
if self.scan_thread and self.scan_thread.is_alive():
|
if self.scan_thread and self.scan_thread.is_alive():
|
||||||
@ -221,7 +236,7 @@ class Scanner:
|
|||||||
# Clear all processing state
|
# Clear all processing state
|
||||||
with self.processing_lock:
|
with self.processing_lock:
|
||||||
self.currently_processing.clear()
|
self.currently_processing.clear()
|
||||||
self.task_queue.clear()
|
self.task_queue = PriorityQueue()
|
||||||
|
|
||||||
# Shutdown executor aggressively
|
# Shutdown executor aggressively
|
||||||
if self.executor:
|
if self.executor:
|
||||||
@ -251,7 +266,7 @@ class Scanner:
|
|||||||
with self.processing_lock:
|
with self.processing_lock:
|
||||||
self.currently_processing.clear()
|
self.currently_processing.clear()
|
||||||
|
|
||||||
self.task_queue.clear()
|
self.task_queue = PriorityQueue()
|
||||||
self.target_retries.clear()
|
self.target_retries.clear()
|
||||||
self.scan_failed_due_to_retries = False
|
self.scan_failed_due_to_retries = False
|
||||||
|
|
||||||
@ -268,7 +283,14 @@ class Scanner:
|
|||||||
|
|
||||||
if clear_graph:
|
if clear_graph:
|
||||||
self.graph.clear()
|
self.graph.clear()
|
||||||
self.current_target = target_domain.lower().strip()
|
|
||||||
|
if force_rescan_target and self.graph.graph.has_node(force_rescan_target):
|
||||||
|
print(f"Forcing rescan of {force_rescan_target}, clearing provider states.")
|
||||||
|
node_data = self.graph.graph.nodes[force_rescan_target]
|
||||||
|
if 'metadata' in node_data and 'provider_states' in node_data['metadata']:
|
||||||
|
node_data['metadata']['provider_states'] = {}
|
||||||
|
|
||||||
|
self.current_target = target.lower().strip()
|
||||||
self.max_depth = max_depth
|
self.max_depth = max_depth
|
||||||
self.current_depth = 0
|
self.current_depth = 0
|
||||||
|
|
||||||
@ -304,95 +326,119 @@ class Scanner:
|
|||||||
self._update_session_state()
|
self._update_session_state()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _execute_scan(self, target_domain: str, max_depth: int) -> None:
|
def _get_priority(self, provider_name):
|
||||||
"""Execute the reconnaissance scan with proper termination handling."""
|
rate_limit = self.config.get_rate_limit(provider_name)
|
||||||
print(f"_execute_scan started for {target_domain} with depth {max_depth}")
|
if rate_limit > 90:
|
||||||
self.executor = ThreadPoolExecutor(max_workers=self.max_workers)
|
return 1 # Highest priority
|
||||||
processed_targets = set()
|
elif rate_limit > 50:
|
||||||
|
return 2
|
||||||
|
else:
|
||||||
|
return 3 # Lowest priority
|
||||||
|
|
||||||
self.task_queue.append((target_domain, 0, False))
|
def _execute_scan(self, target: str, max_depth: int) -> None:
|
||||||
|
"""Execute the reconnaissance scan with proper termination handling."""
|
||||||
|
print(f"_execute_scan started for {target} with depth {max_depth}")
|
||||||
|
self.executor = ThreadPoolExecutor(max_workers=self.max_workers)
|
||||||
|
processed_tasks = set()
|
||||||
|
|
||||||
|
# Initial task population for the main target
|
||||||
|
is_ip = _is_valid_ip(target)
|
||||||
|
initial_providers = self._get_eligible_providers(target, is_ip, False)
|
||||||
|
for provider in initial_providers:
|
||||||
|
provider_name = provider.get_name()
|
||||||
|
self.task_queue.put((self._get_priority(provider_name), (provider_name, target, 0)))
|
||||||
|
self.total_tasks_ever_enqueued += 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.status = ScanStatus.RUNNING
|
self.status = ScanStatus.RUNNING
|
||||||
self._update_session_state()
|
self._update_session_state()
|
||||||
|
|
||||||
enabled_providers = [provider.get_name() for provider in self.providers]
|
enabled_providers = [provider.get_name() for provider in self.providers]
|
||||||
self.logger.log_scan_start(target_domain, max_depth, enabled_providers)
|
self.logger.log_scan_start(target, max_depth, enabled_providers)
|
||||||
self.graph.add_node(target_domain, NodeType.DOMAIN)
|
|
||||||
self._initialize_provider_states(target_domain)
|
|
||||||
|
|
||||||
# **IMPROVED**: Better termination checking in main loop
|
# Determine initial node type
|
||||||
while self.task_queue and not self._is_stop_requested():
|
node_type = NodeType.IP if is_ip else NodeType.DOMAIN
|
||||||
|
self.graph.add_node(target, node_type)
|
||||||
|
|
||||||
|
self._initialize_provider_states(target)
|
||||||
|
|
||||||
|
# Better termination checking in main loop
|
||||||
|
while not self.task_queue.empty() and not self._is_stop_requested():
|
||||||
try:
|
try:
|
||||||
target, depth, is_large_entity_member = self.task_queue.popleft()
|
priority, (provider_name, target_item, depth) = self.task_queue.get()
|
||||||
except IndexError:
|
except IndexError:
|
||||||
# Queue became empty during processing
|
# Queue became empty during processing
|
||||||
break
|
break
|
||||||
|
|
||||||
if target in processed_targets:
|
task_tuple = (provider_name, target_item)
|
||||||
|
if task_tuple in processed_tasks:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if depth > max_depth:
|
if depth > max_depth:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# **NEW**: Track this target as currently processing
|
if self.rate_limiter.is_rate_limited(provider_name, self.config.get_rate_limit(provider_name), 60):
|
||||||
|
self.task_queue.put((priority + 1, (provider_name, target_item, depth))) # Postpone
|
||||||
|
continue
|
||||||
|
|
||||||
with self.processing_lock:
|
with self.processing_lock:
|
||||||
if self._is_stop_requested():
|
if self._is_stop_requested():
|
||||||
print(f"Stop requested before processing {target}")
|
print(f"Stop requested before processing {target_item}")
|
||||||
break
|
break
|
||||||
self.currently_processing.add(target)
|
self.currently_processing.add(target_item)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.current_depth = depth
|
self.current_depth = depth
|
||||||
self.current_indicator = target
|
self.current_indicator = target_item
|
||||||
self._update_session_state()
|
self._update_session_state()
|
||||||
|
|
||||||
# **IMPROVED**: More frequent stop checking during processing
|
|
||||||
if self._is_stop_requested():
|
if self._is_stop_requested():
|
||||||
print(f"Stop requested during processing setup for {target}")
|
print(f"Stop requested during processing setup for {target_item}")
|
||||||
break
|
break
|
||||||
|
|
||||||
new_targets, large_entity_members, success = self._query_providers_for_target(target, depth, is_large_entity_member)
|
provider = next((p for p in self.providers if p.get_name() == provider_name), None)
|
||||||
|
|
||||||
|
if provider:
|
||||||
|
new_targets, large_entity_members, success = self._query_single_provider_for_target(provider, target_item, depth)
|
||||||
|
|
||||||
# **NEW**: Check stop signal after provider queries
|
|
||||||
if self._is_stop_requested():
|
if self._is_stop_requested():
|
||||||
print(f"Stop requested after querying providers for {target}")
|
print(f"Stop requested after querying providers for {target_item}")
|
||||||
break
|
break
|
||||||
|
|
||||||
if not success:
|
if not success:
|
||||||
self.target_retries[target] += 1
|
self.target_retries[task_tuple] += 1
|
||||||
if self.target_retries[target] <= self.config.max_retries_per_target:
|
if self.target_retries[task_tuple] <= self.config.max_retries_per_target:
|
||||||
print(f"Re-queueing target {target} (attempt {self.target_retries[target]})")
|
print(f"Re-queueing task {task_tuple} (attempt {self.target_retries[task_tuple]})")
|
||||||
self.task_queue.append((target, depth, is_large_entity_member))
|
self.task_queue.put((priority, (provider_name, target_item, depth)))
|
||||||
self.tasks_re_enqueued += 1
|
self.tasks_re_enqueued += 1
|
||||||
|
self.total_tasks_ever_enqueued += 1
|
||||||
else:
|
else:
|
||||||
print(f"ERROR: Max retries exceeded for target {target}")
|
print(f"ERROR: Max retries exceeded for task {task_tuple}")
|
||||||
self.scan_failed_due_to_retries = True
|
self.scan_failed_due_to_retries = True
|
||||||
self._log_target_processing_error(target, "Max retries exceeded")
|
self._log_target_processing_error(str(task_tuple), "Max retries exceeded")
|
||||||
else:
|
else:
|
||||||
processed_targets.add(target)
|
processed_tasks.add(task_tuple)
|
||||||
self.indicators_completed += 1
|
self.indicators_completed += 1
|
||||||
|
|
||||||
# **NEW**: Only add new targets if not stopped
|
|
||||||
if not self._is_stop_requested():
|
if not self._is_stop_requested():
|
||||||
for new_target in new_targets:
|
all_new_targets = new_targets.union(large_entity_members)
|
||||||
if new_target not in processed_targets:
|
for new_target in all_new_targets:
|
||||||
self.task_queue.append((new_target, depth + 1, False))
|
is_ip_new = _is_valid_ip(new_target)
|
||||||
|
eligible_providers_new = self._get_eligible_providers(new_target, is_ip_new, False)
|
||||||
for member in large_entity_members:
|
for p_new in eligible_providers_new:
|
||||||
if member not in processed_targets:
|
p_name_new = p_new.get_name()
|
||||||
self.task_queue.append((member, depth, True))
|
if (p_name_new, new_target) not in processed_tasks:
|
||||||
|
new_depth = depth + 1 if new_target in new_targets else depth
|
||||||
|
self.task_queue.put((self._get_priority(p_name_new), (p_name_new, new_target, new_depth)))
|
||||||
|
self.total_tasks_ever_enqueued += 1
|
||||||
finally:
|
finally:
|
||||||
# **NEW**: Always remove from processing set
|
|
||||||
with self.processing_lock:
|
with self.processing_lock:
|
||||||
self.currently_processing.discard(target)
|
self.currently_processing.discard(target_item)
|
||||||
|
|
||||||
# **NEW**: Log termination reason
|
|
||||||
if self._is_stop_requested():
|
if self._is_stop_requested():
|
||||||
print("Scan terminated due to stop request")
|
print("Scan terminated due to stop request")
|
||||||
self.logger.logger.info("Scan terminated by user request")
|
self.logger.logger.info("Scan terminated by user request")
|
||||||
elif not self.task_queue:
|
elif self.task_queue.empty():
|
||||||
print("Scan completed - no more targets to process")
|
print("Scan completed - no more targets to process")
|
||||||
self.logger.logger.info("Scan completed - all targets processed")
|
self.logger.logger.info("Scan completed - all targets processed")
|
||||||
|
|
||||||
@ -402,7 +448,6 @@ class Scanner:
|
|||||||
self.status = ScanStatus.FAILED
|
self.status = ScanStatus.FAILED
|
||||||
self.logger.logger.error(f"Scan failed: {e}")
|
self.logger.logger.error(f"Scan failed: {e}")
|
||||||
finally:
|
finally:
|
||||||
# **NEW**: Clear processing state on exit
|
|
||||||
with self.processing_lock:
|
with self.processing_lock:
|
||||||
self.currently_processing.clear()
|
self.currently_processing.clear()
|
||||||
|
|
||||||
@ -422,18 +467,16 @@ class Scanner:
|
|||||||
print("Final scan statistics:")
|
print("Final scan statistics:")
|
||||||
print(f" - Total nodes: {stats['basic_metrics']['total_nodes']}")
|
print(f" - Total nodes: {stats['basic_metrics']['total_nodes']}")
|
||||||
print(f" - Total edges: {stats['basic_metrics']['total_edges']}")
|
print(f" - Total edges: {stats['basic_metrics']['total_edges']}")
|
||||||
print(f" - Targets processed: {len(processed_targets)}")
|
print(f" - Tasks processed: {len(processed_tasks)}")
|
||||||
|
|
||||||
def _query_providers_for_target(self, target: str, depth: int, dns_only: bool = False) -> Tuple[Set[str], Set[str], bool]:
|
def _query_single_provider_for_target(self, provider: BaseProvider, target: str, depth: int) -> Tuple[Set[str], Set[str], bool]:
|
||||||
"""Query providers for a single target with enhanced stop checking."""
|
|
||||||
# **NEW**: Early termination check
|
|
||||||
if self._is_stop_requested():
|
if self._is_stop_requested():
|
||||||
print(f"Stop requested before querying providers for {target}")
|
print(f"Stop requested before querying {provider.get_name()} for {target}")
|
||||||
return set(), set(), False
|
return set(), set(), False
|
||||||
|
|
||||||
is_ip = _is_valid_ip(target)
|
is_ip = _is_valid_ip(target)
|
||||||
target_type = NodeType.IP if is_ip else NodeType.DOMAIN
|
target_type = NodeType.IP if is_ip else NodeType.DOMAIN
|
||||||
print(f"Querying providers for {target_type.value}: {target} at depth {depth}")
|
print(f"Querying {provider.get_name()} for {target_type.value}: {target} at depth {depth}")
|
||||||
|
|
||||||
self.graph.add_node(target, target_type)
|
self.graph.add_node(target, target_type)
|
||||||
self._initialize_provider_states(target)
|
self._initialize_provider_states(target)
|
||||||
@ -441,27 +484,14 @@ class Scanner:
|
|||||||
new_targets = set()
|
new_targets = set()
|
||||||
large_entity_members = set()
|
large_entity_members = set()
|
||||||
node_attributes = defaultdict(lambda: defaultdict(list))
|
node_attributes = defaultdict(lambda: defaultdict(list))
|
||||||
all_providers_successful = True
|
provider_successful = True
|
||||||
|
|
||||||
eligible_providers = self._get_eligible_providers(target, is_ip, dns_only)
|
|
||||||
|
|
||||||
if not eligible_providers:
|
|
||||||
self._log_no_eligible_providers(target, is_ip)
|
|
||||||
return new_targets, large_entity_members, True
|
|
||||||
|
|
||||||
# **IMPROVED**: Check stop signal before each provider
|
|
||||||
for i, provider in enumerate(eligible_providers):
|
|
||||||
if self._is_stop_requested():
|
|
||||||
print(f"Stop requested while querying provider {i+1}/{len(eligible_providers)} for {target}")
|
|
||||||
all_providers_successful = False
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
provider_results = self._query_single_provider_forensic(provider, target, is_ip, depth)
|
provider_results = self._query_single_provider_forensic(provider, target, is_ip, depth)
|
||||||
if provider_results is None:
|
if provider_results is None:
|
||||||
all_providers_successful = False
|
provider_successful = False
|
||||||
elif not self._is_stop_requested():
|
elif not self._is_stop_requested():
|
||||||
discovered, is_large_entity = self._process_provider_results_forensic(
|
discovered, is_large_entity = self._process_provider_results(
|
||||||
target, provider, provider_results, node_attributes, depth
|
target, provider, provider_results, node_attributes, depth
|
||||||
)
|
)
|
||||||
if is_large_entity:
|
if is_large_entity:
|
||||||
@ -470,12 +500,10 @@ class Scanner:
|
|||||||
new_targets.update(discovered)
|
new_targets.update(discovered)
|
||||||
else:
|
else:
|
||||||
print(f"Stop requested after processing results from {provider.get_name()}")
|
print(f"Stop requested after processing results from {provider.get_name()}")
|
||||||
break
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
all_providers_successful = False
|
provider_successful = False
|
||||||
self._log_provider_error(target, provider.get_name(), str(e))
|
self._log_provider_error(target, provider.get_name(), str(e))
|
||||||
|
|
||||||
# **NEW**: Only update node attributes if not stopped
|
|
||||||
if not self._is_stop_requested():
|
if not self._is_stop_requested():
|
||||||
for node_id, attributes in node_attributes.items():
|
for node_id, attributes in node_attributes.items():
|
||||||
if self.graph.graph.has_node(node_id):
|
if self.graph.graph.has_node(node_id):
|
||||||
@ -483,7 +511,7 @@ class Scanner:
|
|||||||
node_type_to_add = NodeType.IP if node_is_ip else NodeType.DOMAIN
|
node_type_to_add = NodeType.IP if node_is_ip else NodeType.DOMAIN
|
||||||
self.graph.add_node(node_id, node_type_to_add, attributes=attributes)
|
self.graph.add_node(node_id, node_type_to_add, attributes=attributes)
|
||||||
|
|
||||||
return new_targets, large_entity_members, all_providers_successful
|
return new_targets, large_entity_members, provider_successful
|
||||||
|
|
||||||
def stop_scan(self) -> bool:
|
def stop_scan(self) -> bool:
|
||||||
"""Request immediate scan termination with proper cleanup."""
|
"""Request immediate scan termination with proper cleanup."""
|
||||||
@ -502,8 +530,10 @@ class Scanner:
|
|||||||
print(f"Cleared {len(currently_processing_copy)} currently processing targets: {currently_processing_copy}")
|
print(f"Cleared {len(currently_processing_copy)} currently processing targets: {currently_processing_copy}")
|
||||||
|
|
||||||
# **IMPROVED**: Clear task queue and log what was discarded
|
# **IMPROVED**: Clear task queue and log what was discarded
|
||||||
discarded_tasks = list(self.task_queue)
|
discarded_tasks = []
|
||||||
self.task_queue.clear()
|
while not self.task_queue.empty():
|
||||||
|
discarded_tasks.append(self.task_queue.get())
|
||||||
|
self.task_queue = PriorityQueue()
|
||||||
print(f"Discarded {len(discarded_tasks)} pending tasks")
|
print(f"Discarded {len(discarded_tasks)} pending tasks")
|
||||||
|
|
||||||
# **IMPROVED**: Aggressively shut down executor
|
# **IMPROVED**: Aggressively shut down executor
|
||||||
@ -559,11 +589,12 @@ class Scanner:
|
|||||||
'indicators_completed': self.indicators_completed,
|
'indicators_completed': self.indicators_completed,
|
||||||
'tasks_re_enqueued': self.tasks_re_enqueued,
|
'tasks_re_enqueued': self.tasks_re_enqueued,
|
||||||
'progress_percentage': self._calculate_progress(),
|
'progress_percentage': self._calculate_progress(),
|
||||||
|
'total_tasks_ever_enqueued': self.total_tasks_ever_enqueued,
|
||||||
'enabled_providers': [provider.get_name() for provider in self.providers],
|
'enabled_providers': [provider.get_name() for provider in self.providers],
|
||||||
'graph_statistics': self.graph.get_statistics(),
|
'graph_statistics': self.graph.get_statistics(),
|
||||||
'task_queue_size': len(self.task_queue),
|
'task_queue_size': self.task_queue.qsize(),
|
||||||
'currently_processing_count': currently_processing_count, # **NEW**
|
'currently_processing_count': currently_processing_count,
|
||||||
'currently_processing': currently_processing_list[:5] # **NEW**: Show first 5 for debugging
|
'currently_processing': currently_processing_list[:5]
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"ERROR: Exception in get_scan_status: {e}")
|
print(f"ERROR: Exception in get_scan_status: {e}")
|
||||||
@ -680,7 +711,7 @@ class Scanner:
|
|||||||
|
|
||||||
self.logger.logger.info(f"Provider state updated: {target} -> {provider_name} -> {status} ({results_count} results)")
|
self.logger.logger.info(f"Provider state updated: {target} -> {provider_name} -> {status} ({results_count} results)")
|
||||||
|
|
||||||
def _process_provider_results_forensic(self, target: str, provider, results: List,
|
def _process_provider_results(self, target: str, provider, results: List,
|
||||||
node_attributes: Dict, current_depth: int) -> Tuple[Set[str], bool]:
|
node_attributes: Dict, current_depth: int) -> Tuple[Set[str], bool]:
|
||||||
"""Process provider results, returns (discovered_targets, is_large_entity)."""
|
"""Process provider results, returns (discovered_targets, is_large_entity)."""
|
||||||
provider_name = provider.get_name()
|
provider_name = provider.get_name()
|
||||||
@ -710,8 +741,14 @@ class Scanner:
|
|||||||
discovery_method=f"{provider_name}_query_depth_{current_depth}"
|
discovery_method=f"{provider_name}_query_depth_{current_depth}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Collect attributes for the source node
|
||||||
self._collect_node_attributes(source, provider_name, rel_type, rel_target, raw_data, node_attributes[source])
|
self._collect_node_attributes(source, provider_name, rel_type, rel_target, raw_data, node_attributes[source])
|
||||||
|
|
||||||
|
# If the relationship is asn_membership, collect attributes for the target ASN node
|
||||||
|
if rel_type == 'asn_membership':
|
||||||
|
self._collect_node_attributes(rel_target, provider_name, rel_type, source, raw_data, node_attributes[rel_target])
|
||||||
|
|
||||||
|
|
||||||
if isinstance(rel_target, list):
|
if isinstance(rel_target, list):
|
||||||
# If the target is a list, iterate and process each item
|
# If the target is a list, iterate and process each item
|
||||||
for single_target in rel_target:
|
for single_target in rel_target:
|
||||||
@ -763,6 +800,7 @@ class Scanner:
|
|||||||
elif _is_valid_ip(targets[0]):
|
elif _is_valid_ip(targets[0]):
|
||||||
node_type = 'ip'
|
node_type = 'ip'
|
||||||
|
|
||||||
|
# We still create the nodes so they exist in the graph, they are just not processed for edges yet.
|
||||||
for target in targets:
|
for target in targets:
|
||||||
self.graph.add_node(target, NodeType.DOMAIN if node_type == 'domain' else NodeType.IP)
|
self.graph.add_node(target, NodeType.DOMAIN if node_type == 'domain' else NodeType.IP)
|
||||||
|
|
||||||
@ -788,6 +826,73 @@ class Scanner:
|
|||||||
|
|
||||||
return set(targets)
|
return set(targets)
|
||||||
|
|
||||||
|
def extract_node_from_large_entity(self, large_entity_id: str, node_id_to_extract: str) -> bool:
|
||||||
|
"""
|
||||||
|
Extracts a node from a large entity, re-creates its original edge, and
|
||||||
|
re-queues it for full scanning.
|
||||||
|
"""
|
||||||
|
if not self.graph.graph.has_node(large_entity_id):
|
||||||
|
print(f"ERROR: Large entity {large_entity_id} not found.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 1. Get the original source node that discovered the large entity
|
||||||
|
predecessors = list(self.graph.graph.predecessors(large_entity_id))
|
||||||
|
if not predecessors:
|
||||||
|
print(f"ERROR: No source node found for large entity {large_entity_id}.")
|
||||||
|
return False
|
||||||
|
source_node_id = predecessors[0]
|
||||||
|
|
||||||
|
# Get the original edge data to replicate it for the extracted node
|
||||||
|
original_edge_data = self.graph.graph.get_edge_data(source_node_id, large_entity_id)
|
||||||
|
if not original_edge_data:
|
||||||
|
print(f"ERROR: Could not find original edge data from {source_node_id} to {large_entity_id}.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 2. Modify the graph data structure first
|
||||||
|
success = self.graph.extract_node_from_large_entity(large_entity_id, node_id_to_extract)
|
||||||
|
if not success:
|
||||||
|
print(f"ERROR: Node {node_id_to_extract} could not be removed from {large_entity_id}'s attributes.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 3. Create the direct edge from the original source to the newly extracted node
|
||||||
|
print(f"Re-creating direct edge from {source_node_id} to extracted node {node_id_to_extract}")
|
||||||
|
self.graph.add_edge(
|
||||||
|
source_id=source_node_id,
|
||||||
|
target_id=node_id_to_extract,
|
||||||
|
relationship_type=original_edge_data.get('relationship_type', 'extracted_from_large_entity'),
|
||||||
|
confidence_score=original_edge_data.get('confidence_score', 0.85), # Slightly lower confidence
|
||||||
|
source_provider=original_edge_data.get('source_provider', 'unknown'),
|
||||||
|
raw_data={'context': f'Extracted from large entity {large_entity_id}'}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Re-queue the extracted node for full processing by all eligible providers
|
||||||
|
print(f"Re-queueing extracted node {node_id_to_extract} for full reconnaissance...")
|
||||||
|
is_ip = _is_valid_ip(node_id_to_extract)
|
||||||
|
current_depth = self.graph.graph.nodes[large_entity_id].get('attributes', {}).get('discovery_depth', 0)
|
||||||
|
|
||||||
|
eligible_providers = self._get_eligible_providers(node_id_to_extract, is_ip, False)
|
||||||
|
for provider in eligible_providers:
|
||||||
|
provider_name = provider.get_name()
|
||||||
|
self.task_queue.put((self._get_priority(provider_name), (provider_name, node_id_to_extract, current_depth)))
|
||||||
|
self.total_tasks_ever_enqueued += 1
|
||||||
|
|
||||||
|
# 5. If the scanner is not running, we need to kickstart it to process this one item.
|
||||||
|
if self.status != ScanStatus.RUNNING:
|
||||||
|
print("Scanner is idle. Starting a mini-scan to process the extracted node.")
|
||||||
|
self.status = ScanStatus.RUNNING
|
||||||
|
self._update_session_state()
|
||||||
|
|
||||||
|
if not self.scan_thread or not self.scan_thread.is_alive():
|
||||||
|
self.scan_thread = threading.Thread(
|
||||||
|
target=self._execute_scan,
|
||||||
|
args=(self.current_target, self.max_depth),
|
||||||
|
daemon=True
|
||||||
|
)
|
||||||
|
self.scan_thread.start()
|
||||||
|
|
||||||
|
print(f"Successfully extracted and re-queued {node_id_to_extract} from {large_entity_id}.")
|
||||||
|
return True
|
||||||
|
|
||||||
def _collect_node_attributes(self, node_id: str, provider_name: str, rel_type: str,
|
def _collect_node_attributes(self, node_id: str, provider_name: str, rel_type: str,
|
||||||
target: str, raw_data: Dict[str, Any], attributes: Dict[str, Any]) -> None:
|
target: str, raw_data: Dict[str, Any], attributes: Dict[str, Any]) -> None:
|
||||||
"""Collect and organize attributes for a node."""
|
"""Collect and organize attributes for a node."""
|
||||||
@ -810,18 +915,22 @@ class Scanner:
|
|||||||
attributes.setdefault('related_domains_san', []).append(target)
|
attributes.setdefault('related_domains_san', []).append(target)
|
||||||
|
|
||||||
elif provider_name == 'shodan':
|
elif provider_name == 'shodan':
|
||||||
|
# This logic will now apply to the correct node (ASN or IP)
|
||||||
shodan_attributes = attributes.setdefault('shodan', {})
|
shodan_attributes = attributes.setdefault('shodan', {})
|
||||||
for key, value in raw_data.items():
|
for key, value in raw_data.items():
|
||||||
if key not in shodan_attributes or not shodan_attributes.get(key):
|
if key not in shodan_attributes or not shodan_attributes.get(key):
|
||||||
shodan_attributes[key] = value
|
shodan_attributes[key] = value
|
||||||
|
|
||||||
|
if _is_valid_ip(node_id):
|
||||||
|
if 'ports' in raw_data:
|
||||||
|
attributes['ports'] = raw_data['ports']
|
||||||
|
if 'os' in raw_data and raw_data['os']:
|
||||||
|
attributes['os'] = raw_data['os']
|
||||||
|
|
||||||
if rel_type == "asn_membership":
|
if rel_type == "asn_membership":
|
||||||
attributes['asn'] = {
|
# This is the key change: these attributes are for the target (the ASN),
|
||||||
'id': target,
|
# not the source (the IP). We will add them to the ASN node later.
|
||||||
'description': raw_data.get('org', ''),
|
pass
|
||||||
'isp': raw_data.get('isp', ''),
|
|
||||||
'country': raw_data.get('country', '')
|
|
||||||
}
|
|
||||||
|
|
||||||
record_type_name = rel_type
|
record_type_name = rel_type
|
||||||
if record_type_name not in attributes:
|
if record_type_name not in attributes:
|
||||||
@ -848,10 +957,9 @@ class Scanner:
|
|||||||
|
|
||||||
def _calculate_progress(self) -> float:
|
def _calculate_progress(self) -> float:
|
||||||
"""Calculate scan progress percentage based on task completion."""
|
"""Calculate scan progress percentage based on task completion."""
|
||||||
total_tasks = self.indicators_completed + len(self.task_queue)
|
if self.total_tasks_ever_enqueued == 0:
|
||||||
if total_tasks == 0:
|
|
||||||
return 0.0
|
return 0.0
|
||||||
return min(100.0, (self.indicators_completed / total_tasks) * 100)
|
return min(100.0, (self.indicators_completed / self.total_tasks_ever_enqueued) * 100)
|
||||||
|
|
||||||
def get_graph_data(self) -> Dict[str, Any]:
|
def get_graph_data(self) -> Dict[str, Any]:
|
||||||
"""Get current graph data for visualization."""
|
"""Get current graph data for visualization."""
|
||||||
|
@ -3,14 +3,15 @@ Data provider modules for DNSRecon.
|
|||||||
Contains implementations for various reconnaissance data sources.
|
Contains implementations for various reconnaissance data sources.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from .base_provider import BaseProvider, RateLimiter
|
from .base_provider import BaseProvider
|
||||||
from .crtsh_provider import CrtShProvider
|
from .crtsh_provider import CrtShProvider
|
||||||
from .dns_provider import DNSProvider
|
from .dns_provider import DNSProvider
|
||||||
from .shodan_provider import ShodanProvider
|
from .shodan_provider import ShodanProvider
|
||||||
|
from core.rate_limiter import GlobalRateLimiter
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'BaseProvider',
|
'BaseProvider',
|
||||||
'RateLimiter',
|
'GlobalRateLimiter',
|
||||||
'CrtShProvider',
|
'CrtShProvider',
|
||||||
'DNSProvider',
|
'DNSProvider',
|
||||||
'ShodanProvider'
|
'ShodanProvider'
|
||||||
|
@ -7,40 +7,7 @@ from abc import ABC, abstractmethod
|
|||||||
from typing import List, Dict, Any, Optional, Tuple
|
from typing import List, Dict, Any, Optional, Tuple
|
||||||
|
|
||||||
from core.logger import get_forensic_logger
|
from core.logger import get_forensic_logger
|
||||||
|
from core.rate_limiter import GlobalRateLimiter
|
||||||
|
|
||||||
class RateLimiter:
|
|
||||||
"""Simple rate limiter for API calls."""
|
|
||||||
|
|
||||||
def __init__(self, requests_per_minute: int):
|
|
||||||
"""
|
|
||||||
Initialize rate limiter.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
requests_per_minute: Maximum requests allowed per minute
|
|
||||||
"""
|
|
||||||
self.requests_per_minute = requests_per_minute
|
|
||||||
self.min_interval = 60.0 / requests_per_minute
|
|
||||||
self.last_request_time = 0
|
|
||||||
|
|
||||||
def __getstate__(self):
|
|
||||||
"""RateLimiter is fully picklable, return full state."""
|
|
||||||
return self.__dict__.copy()
|
|
||||||
|
|
||||||
def __setstate__(self, state):
|
|
||||||
"""Restore RateLimiter state."""
|
|
||||||
self.__dict__.update(state)
|
|
||||||
|
|
||||||
def wait_if_needed(self) -> None:
|
|
||||||
"""Wait if necessary to respect rate limits."""
|
|
||||||
current_time = time.time()
|
|
||||||
time_since_last = current_time - self.last_request_time
|
|
||||||
|
|
||||||
if time_since_last < self.min_interval:
|
|
||||||
sleep_time = self.min_interval - time_since_last
|
|
||||||
time.sleep(sleep_time)
|
|
||||||
|
|
||||||
self.last_request_time = time.time()
|
|
||||||
|
|
||||||
|
|
||||||
class BaseProvider(ABC):
|
class BaseProvider(ABC):
|
||||||
@ -68,11 +35,9 @@ class BaseProvider(ABC):
|
|||||||
# Fallback to global config for backwards compatibility
|
# Fallback to global config for backwards compatibility
|
||||||
from config import config as global_config
|
from config import config as global_config
|
||||||
self.config = global_config
|
self.config = global_config
|
||||||
actual_rate_limit = rate_limit
|
|
||||||
actual_timeout = timeout
|
actual_timeout = timeout
|
||||||
|
|
||||||
self.name = name
|
self.name = name
|
||||||
self.rate_limiter = RateLimiter(actual_rate_limit)
|
|
||||||
self.timeout = actual_timeout
|
self.timeout = actual_timeout
|
||||||
self._local = threading.local()
|
self._local = threading.local()
|
||||||
self.logger = get_forensic_logger()
|
self.logger = get_forensic_logger()
|
||||||
@ -172,8 +137,6 @@ class BaseProvider(ABC):
|
|||||||
print(f"Request cancelled before start: {url}")
|
print(f"Request cancelled before start: {url}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
self.rate_limiter.wait_if_needed()
|
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
response = None
|
response = None
|
||||||
error = None
|
error = None
|
||||||
@ -297,5 +260,5 @@ class BaseProvider(ABC):
|
|||||||
'failed_requests': self.failed_requests,
|
'failed_requests': self.failed_requests,
|
||||||
'success_rate': (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 0,
|
'success_rate': (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 0,
|
||||||
'relationships_found': self.total_relationships_found,
|
'relationships_found': self.total_relationships_found,
|
||||||
'rate_limit': self.rate_limiter.requests_per_minute
|
'rate_limit': self.config.get_rate_limit(self.name)
|
||||||
}
|
}
|
@ -514,11 +514,19 @@ class CrtShProvider(BaseProvider):
|
|||||||
shared = []
|
shared = []
|
||||||
|
|
||||||
# Create a set of certificate IDs from the first list for quick lookup
|
# Create a set of certificate IDs from the first list for quick lookup
|
||||||
cert1_ids = {cert.get('certificate_id') for cert in certs1 if cert.get('certificate_id')}
|
# <<< FIX: Added robust type checking to handle potentially malformed API data
|
||||||
|
cert1_ids = set()
|
||||||
|
for cert in certs1:
|
||||||
|
cert_id = cert.get('certificate_id')
|
||||||
|
# Ensure the ID is not None and is a hashable type before adding to the set
|
||||||
|
if cert_id and isinstance(cert_id, (int, str, float, bool, tuple)):
|
||||||
|
cert1_ids.add(cert_id)
|
||||||
|
|
||||||
# Find certificates in the second list that match
|
# Find certificates in the second list that match
|
||||||
for cert in certs2:
|
for cert in certs2:
|
||||||
if cert.get('certificate_id') in cert1_ids:
|
cert_id = cert.get('certificate_id')
|
||||||
|
if cert_id and isinstance(cert_id, (int, str, float, bool, tuple)):
|
||||||
|
if cert_id in cert1_ids:
|
||||||
shared.append(cert)
|
shared.append(cert)
|
||||||
|
|
||||||
return shared
|
return shared
|
||||||
@ -541,7 +549,8 @@ class CrtShProvider(BaseProvider):
|
|||||||
'expires_soon_count': 0,
|
'expires_soon_count': 0,
|
||||||
'unique_issuers': [],
|
'unique_issuers': [],
|
||||||
'latest_certificate': None,
|
'latest_certificate': None,
|
||||||
'has_valid_cert': False
|
'has_valid_cert': False,
|
||||||
|
'certificate_details': [] # Always include empty list
|
||||||
}
|
}
|
||||||
|
|
||||||
valid_count = sum(1 for cert in certificates if cert.get('is_currently_valid'))
|
valid_count = sum(1 for cert in certificates if cert.get('is_currently_valid'))
|
||||||
@ -565,6 +574,13 @@ class CrtShProvider(BaseProvider):
|
|||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Sort certificates by date for better display (newest first)
|
||||||
|
sorted_certificates = sorted(
|
||||||
|
certificates,
|
||||||
|
key=lambda c: self._get_certificate_sort_date(c),
|
||||||
|
reverse=True
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'total_certificates': len(certificates),
|
'total_certificates': len(certificates),
|
||||||
'valid_certificates': valid_count,
|
'valid_certificates': valid_count,
|
||||||
@ -573,9 +589,35 @@ class CrtShProvider(BaseProvider):
|
|||||||
'unique_issuers': unique_issuers,
|
'unique_issuers': unique_issuers,
|
||||||
'latest_certificate': latest_cert,
|
'latest_certificate': latest_cert,
|
||||||
'has_valid_cert': valid_count > 0,
|
'has_valid_cert': valid_count > 0,
|
||||||
'certificate_details': certificates # Full details for forensic analysis
|
'certificate_details': sorted_certificates # Include full certificate details
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def _get_certificate_sort_date(self, cert: Dict[str, Any]) -> datetime:
|
||||||
|
"""
|
||||||
|
Get a sortable date from certificate data for chronological ordering.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
cert: Certificate metadata dictionary
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Datetime object for sorting (falls back to epoch if parsing fails)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Try not_before first (issue date)
|
||||||
|
if cert.get('not_before'):
|
||||||
|
return self._parse_certificate_date(cert['not_before'])
|
||||||
|
|
||||||
|
# Fall back to entry_timestamp if available
|
||||||
|
if cert.get('entry_timestamp'):
|
||||||
|
return self._parse_certificate_date(cert['entry_timestamp'])
|
||||||
|
|
||||||
|
# Last resort - return a very old date for certificates without dates
|
||||||
|
return datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
# If all parsing fails, return epoch
|
||||||
|
return datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
def _calculate_domain_relationship_confidence(self, domain1: str, domain2: str,
|
def _calculate_domain_relationship_confidence(self, domain1: str, domain2: str,
|
||||||
shared_certificates: List[Dict[str, Any]],
|
shared_certificates: List[Dict[str, Any]],
|
||||||
all_discovered_domains: Set[str]) -> float:
|
all_discovered_domains: Set[str]) -> float:
|
||||||
|
@ -1,15 +1,20 @@
|
|||||||
# dnsrecon/providers/shodan_provider.py
|
# dnsrecon/providers/shodan_provider.py
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
from typing import List, Dict, Any, Tuple
|
from typing import List, Dict, Any, Tuple
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import requests
|
||||||
|
|
||||||
from .base_provider import BaseProvider
|
from .base_provider import BaseProvider
|
||||||
from utils.helpers import _is_valid_ip, _is_valid_domain
|
from utils.helpers import _is_valid_ip, _is_valid_domain
|
||||||
|
|
||||||
|
|
||||||
class ShodanProvider(BaseProvider):
|
class ShodanProvider(BaseProvider):
|
||||||
"""
|
"""
|
||||||
Provider for querying Shodan API for IP address and hostname information.
|
Provider for querying Shodan API for IP address information.
|
||||||
Now uses session-specific API keys.
|
Now uses session-specific API keys, is limited to IP-only queries, and includes caching.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, name=None, session_config=None):
|
def __init__(self, name=None, session_config=None):
|
||||||
@ -23,6 +28,10 @@ class ShodanProvider(BaseProvider):
|
|||||||
self.base_url = "https://api.shodan.io"
|
self.base_url = "https://api.shodan.io"
|
||||||
self.api_key = self.config.get_api_key('shodan')
|
self.api_key = self.config.get_api_key('shodan')
|
||||||
|
|
||||||
|
# Initialize cache directory
|
||||||
|
self.cache_dir = Path('cache') / 'shodan'
|
||||||
|
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
def is_available(self) -> bool:
|
def is_available(self) -> bool:
|
||||||
"""Check if Shodan provider is available (has valid API key in this session)."""
|
"""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
|
return self.api_key is not None and len(self.api_key.strip()) > 0
|
||||||
@ -33,7 +42,7 @@ class ShodanProvider(BaseProvider):
|
|||||||
|
|
||||||
def get_display_name(self) -> str:
|
def get_display_name(self) -> str:
|
||||||
"""Return the provider display name for the UI."""
|
"""Return the provider display name for the UI."""
|
||||||
return "shodan"
|
return "Shodan"
|
||||||
|
|
||||||
def requires_api_key(self) -> bool:
|
def requires_api_key(self) -> bool:
|
||||||
"""Return True if the provider requires an API key."""
|
"""Return True if the provider requires an API key."""
|
||||||
@ -41,267 +50,146 @@ class ShodanProvider(BaseProvider):
|
|||||||
|
|
||||||
def get_eligibility(self) -> Dict[str, bool]:
|
def get_eligibility(self) -> Dict[str, bool]:
|
||||||
"""Return a dictionary indicating if the provider can query domains and/or IPs."""
|
"""Return a dictionary indicating if the provider can query domains and/or IPs."""
|
||||||
return {'domains': True, 'ips': True}
|
return {'domains': False, 'ips': True}
|
||||||
|
|
||||||
|
def _get_cache_file_path(self, ip: str) -> Path:
|
||||||
|
"""Generate cache file path for an IP address."""
|
||||||
|
safe_ip = ip.replace('.', '_').replace(':', '_')
|
||||||
|
return self.cache_dir / f"{safe_ip}.json"
|
||||||
|
|
||||||
|
def _get_cache_status(self, cache_file_path: Path) -> str:
|
||||||
|
"""
|
||||||
|
Check cache status for an IP.
|
||||||
|
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:
|
||||||
|
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
|
||||||
|
|
||||||
|
cache_timeout = self.config.cache_timeout_hours
|
||||||
|
if hours_since_query < cache_timeout:
|
||||||
|
return "fresh"
|
||||||
|
else:
|
||||||
|
return "stale"
|
||||||
|
|
||||||
|
except (json.JSONDecodeError, ValueError, KeyError):
|
||||||
|
return "stale"
|
||||||
|
|
||||||
|
def _load_from_cache(self, cache_file_path: Path) -> Dict[str, Any]:
|
||||||
|
"""Load Shodan data from a cache file."""
|
||||||
|
try:
|
||||||
|
with open(cache_file_path, 'r') as f:
|
||||||
|
return json.load(f)
|
||||||
|
except (json.JSONDecodeError, FileNotFoundError):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _save_to_cache(self, cache_file_path: Path, data: Dict[str, Any]) -> None:
|
||||||
|
"""Save Shodan data to a cache file."""
|
||||||
|
try:
|
||||||
|
data['last_upstream_query'] = datetime.now(timezone.utc).isoformat()
|
||||||
|
with open(cache_file_path, 'w') as f:
|
||||||
|
json.dump(data, f, separators=(',', ':'))
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.logger.warning(f"Failed to save Shodan cache for {cache_file_path.name}: {e}")
|
||||||
|
|
||||||
def query_domain(self, domain: str) -> List[Tuple[str, str, str, float, Dict[str, Any]]]:
|
def query_domain(self, domain: str) -> List[Tuple[str, str, str, float, Dict[str, Any]]]:
|
||||||
"""
|
"""
|
||||||
Query Shodan for information about a domain.
|
Domain queries are no longer supported for the Shodan provider.
|
||||||
Uses Shodan's hostname search to find associated IPs.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
domain: Domain to investigate
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of relationships discovered from Shodan data
|
|
||||||
"""
|
"""
|
||||||
if not _is_valid_domain(domain) or not self.is_available():
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
relationships = []
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Search for hostname in Shodan
|
|
||||||
search_query = f"hostname:{domain}"
|
|
||||||
url = f"{self.base_url}/shodan/host/search"
|
|
||||||
params = {
|
|
||||||
'key': self.api_key,
|
|
||||||
'query': search_query,
|
|
||||||
'minify': True # Get minimal data to reduce bandwidth
|
|
||||||
}
|
|
||||||
|
|
||||||
response = self.make_request(url, method="GET", params=params, target_indicator=domain)
|
|
||||||
|
|
||||||
if not response or response.status_code != 200:
|
|
||||||
return []
|
|
||||||
|
|
||||||
data = response.json()
|
|
||||||
|
|
||||||
if 'matches' not in data:
|
|
||||||
return []
|
|
||||||
|
|
||||||
# Process search results
|
|
||||||
for match in data['matches']:
|
|
||||||
ip_address = match.get('ip_str')
|
|
||||||
hostnames = match.get('hostnames', [])
|
|
||||||
|
|
||||||
if ip_address and domain in hostnames:
|
|
||||||
raw_data = {
|
|
||||||
'ip_address': ip_address,
|
|
||||||
'hostnames': hostnames,
|
|
||||||
'country': match.get('location', {}).get('country_name', ''),
|
|
||||||
'city': match.get('location', {}).get('city', ''),
|
|
||||||
'isp': match.get('isp', ''),
|
|
||||||
'org': match.get('org', ''),
|
|
||||||
'ports': match.get('ports', []),
|
|
||||||
'last_update': match.get('last_update', '')
|
|
||||||
}
|
|
||||||
|
|
||||||
relationships.append((
|
|
||||||
domain,
|
|
||||||
ip_address,
|
|
||||||
'a_record', # Domain resolves to IP
|
|
||||||
0.8,
|
|
||||||
raw_data
|
|
||||||
))
|
|
||||||
|
|
||||||
self.log_relationship_discovery(
|
|
||||||
source_node=domain,
|
|
||||||
target_node=ip_address,
|
|
||||||
relationship_type='a_record',
|
|
||||||
confidence_score=0.8,
|
|
||||||
raw_data=raw_data,
|
|
||||||
discovery_method="shodan_hostname_search"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Also create relationships to other hostnames on the same IP
|
|
||||||
for hostname in hostnames:
|
|
||||||
if hostname != domain and _is_valid_domain(hostname):
|
|
||||||
hostname_raw_data = {
|
|
||||||
'shared_ip': ip_address,
|
|
||||||
'all_hostnames': hostnames,
|
|
||||||
'discovery_context': 'shared_hosting'
|
|
||||||
}
|
|
||||||
|
|
||||||
relationships.append((
|
|
||||||
domain,
|
|
||||||
hostname,
|
|
||||||
'passive_dns', # Shared hosting relationship
|
|
||||||
0.6, # Lower confidence for shared hosting
|
|
||||||
hostname_raw_data
|
|
||||||
))
|
|
||||||
|
|
||||||
self.log_relationship_discovery(
|
|
||||||
source_node=domain,
|
|
||||||
target_node=hostname,
|
|
||||||
relationship_type='passive_dns',
|
|
||||||
confidence_score=0.6,
|
|
||||||
raw_data=hostname_raw_data,
|
|
||||||
discovery_method="shodan_shared_hosting"
|
|
||||||
)
|
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
self.logger.logger.error(f"Failed to parse JSON response from Shodan: {e}")
|
|
||||||
|
|
||||||
return relationships
|
|
||||||
|
|
||||||
def query_ip(self, ip: str) -> List[Tuple[str, str, str, float, Dict[str, Any]]]:
|
def query_ip(self, ip: str) -> List[Tuple[str, str, str, float, Dict[str, Any]]]:
|
||||||
"""
|
"""
|
||||||
Query Shodan for information about an IP address.
|
Query Shodan for information about an IP address, with caching.
|
||||||
|
|
||||||
Args:
|
|
||||||
ip: IP address to investigate
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of relationships discovered from Shodan IP data
|
|
||||||
"""
|
"""
|
||||||
if not _is_valid_ip(ip) or not self.is_available():
|
if not _is_valid_ip(ip) or not self.is_available():
|
||||||
return []
|
return []
|
||||||
|
|
||||||
relationships = []
|
cache_file = self._get_cache_file_path(ip)
|
||||||
|
cache_status = self._get_cache_status(cache_file)
|
||||||
|
|
||||||
|
data = {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Query Shodan host information
|
if cache_status == "fresh":
|
||||||
|
data = self._load_from_cache(cache_file)
|
||||||
|
self.logger.logger.info(f"Using cached Shodan data for {ip}")
|
||||||
|
else: # "stale" or "not_found"
|
||||||
url = f"{self.base_url}/shodan/host/{ip}"
|
url = f"{self.base_url}/shodan/host/{ip}"
|
||||||
params = {'key': self.api_key}
|
params = {'key': self.api_key}
|
||||||
|
|
||||||
response = self.make_request(url, method="GET", params=params, target_indicator=ip)
|
response = self.make_request(url, method="GET", params=params, target_indicator=ip)
|
||||||
|
|
||||||
if not response or response.status_code != 200:
|
if response and response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
self._save_to_cache(cache_file, data)
|
||||||
|
elif cache_status == "stale":
|
||||||
|
# If API fails on a stale cache, use the old data
|
||||||
|
data = self._load_from_cache(cache_file)
|
||||||
|
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
self.logger.logger.error(f"Shodan API query failed for {ip}: {e}")
|
||||||
|
if cache_status == "stale":
|
||||||
|
data = self._load_from_cache(cache_file)
|
||||||
|
|
||||||
|
if not data:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
data = response.json()
|
return self._process_shodan_data(ip, data)
|
||||||
|
|
||||||
|
def _process_shodan_data(self, ip: str, data: Dict[str, Any]) -> List[Tuple[str, str, str, float, Dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
Process Shodan data to extract relationships.
|
||||||
|
"""
|
||||||
|
relationships = []
|
||||||
|
|
||||||
# Extract hostname relationships
|
# Extract hostname relationships
|
||||||
hostnames = data.get('hostnames', [])
|
hostnames = data.get('hostnames', [])
|
||||||
for hostname in hostnames:
|
for hostname in hostnames:
|
||||||
if _is_valid_domain(hostname):
|
if _is_valid_domain(hostname):
|
||||||
raw_data = {
|
|
||||||
'ip_address': ip,
|
|
||||||
'hostname': hostname,
|
|
||||||
'country': data.get('country_name', ''),
|
|
||||||
'city': data.get('city', ''),
|
|
||||||
'isp': data.get('isp', ''),
|
|
||||||
'org': data.get('org', ''),
|
|
||||||
'asn': data.get('asn', ''),
|
|
||||||
'ports': data.get('ports', []),
|
|
||||||
'last_update': data.get('last_update', ''),
|
|
||||||
'os': data.get('os', '')
|
|
||||||
}
|
|
||||||
|
|
||||||
relationships.append((
|
relationships.append((
|
||||||
ip,
|
ip,
|
||||||
hostname,
|
hostname,
|
||||||
'a_record', # IP resolves to hostname
|
'a_record',
|
||||||
0.8,
|
0.8,
|
||||||
raw_data
|
data
|
||||||
))
|
))
|
||||||
|
|
||||||
self.log_relationship_discovery(
|
self.log_relationship_discovery(
|
||||||
source_node=ip,
|
source_node=ip,
|
||||||
target_node=hostname,
|
target_node=hostname,
|
||||||
relationship_type='a_record',
|
relationship_type='a_record',
|
||||||
confidence_score=0.8,
|
confidence_score=0.8,
|
||||||
raw_data=raw_data,
|
raw_data=data,
|
||||||
discovery_method="shodan_host_lookup"
|
discovery_method="shodan_host_lookup"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Extract ASN relationship if available
|
# Extract ASN relationship
|
||||||
asn = data.get('asn')
|
asn = data.get('asn')
|
||||||
if asn:
|
if asn:
|
||||||
# Ensure the ASN starts with "AS"
|
asn_name = f"AS{asn[2:]}" if isinstance(asn, str) and asn.startswith('AS') else f"AS{asn}"
|
||||||
if isinstance(asn, str) and asn.startswith('AS'):
|
|
||||||
asn_name = asn
|
|
||||||
asn_number = asn[2:]
|
|
||||||
else:
|
|
||||||
asn_name = f"AS{asn}"
|
|
||||||
asn_number = str(asn)
|
|
||||||
|
|
||||||
asn_raw_data = {
|
|
||||||
'ip_address': ip,
|
|
||||||
'asn': asn_number,
|
|
||||||
'isp': data.get('isp', ''),
|
|
||||||
'org': data.get('org', '')
|
|
||||||
}
|
|
||||||
|
|
||||||
relationships.append((
|
relationships.append((
|
||||||
ip,
|
ip,
|
||||||
asn_name,
|
asn_name,
|
||||||
'asn_membership',
|
'asn_membership',
|
||||||
0.7,
|
0.7,
|
||||||
asn_raw_data
|
data
|
||||||
))
|
))
|
||||||
|
|
||||||
self.log_relationship_discovery(
|
self.log_relationship_discovery(
|
||||||
source_node=ip,
|
source_node=ip,
|
||||||
target_node=asn_name,
|
target_node=asn_name,
|
||||||
relationship_type='asn_membership',
|
relationship_type='asn_membership',
|
||||||
confidence_score=0.7,
|
confidence_score=0.7,
|
||||||
raw_data=asn_raw_data,
|
raw_data=data,
|
||||||
discovery_method="shodan_asn_lookup"
|
discovery_method="shodan_asn_lookup"
|
||||||
)
|
)
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
self.logger.logger.error(f"Failed to parse JSON response from Shodan: {e}")
|
|
||||||
|
|
||||||
return relationships
|
return relationships
|
||||||
|
|
||||||
def search_by_organization(self, org_name: str) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
Search Shodan for hosts belonging to a specific organization.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
org_name: Organization name to search for
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of host information dictionaries
|
|
||||||
"""
|
|
||||||
if not self.is_available():
|
|
||||||
return []
|
|
||||||
|
|
||||||
try:
|
|
||||||
search_query = f"org:\"{org_name}\""
|
|
||||||
url = f"{self.base_url}/shodan/host/search"
|
|
||||||
params = {
|
|
||||||
'key': self.api_key,
|
|
||||||
'query': search_query,
|
|
||||||
'minify': True
|
|
||||||
}
|
|
||||||
|
|
||||||
response = self.make_request(url, method="GET", params=params, target_indicator=org_name)
|
|
||||||
|
|
||||||
if response and response.status_code == 200:
|
|
||||||
data = response.json()
|
|
||||||
return data.get('matches', [])
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.logger.error(f"Error searching Shodan by organization {org_name}: {e}")
|
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_host_services(self, ip: str) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
Get service information for a specific IP address.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ip: IP address to query
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of service information dictionaries
|
|
||||||
"""
|
|
||||||
if not _is_valid_ip(ip) or not self.is_available():
|
|
||||||
return []
|
|
||||||
|
|
||||||
try:
|
|
||||||
url = f"{self.base_url}/shodan/host/{ip}"
|
|
||||||
params = {'key': self.api_key}
|
|
||||||
|
|
||||||
response = self.make_request(url, method="GET", params=params, target_indicator=ip)
|
|
||||||
|
|
||||||
if response and response.status_code == 200:
|
|
||||||
data = response.json()
|
|
||||||
return data.get('data', []) # Service banners
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.logger.error(f"Error getting Shodan services for IP {ip}: {e}")
|
|
||||||
|
|
||||||
return []
|
|
1884
static/css/main.css
1884
static/css/main.css
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,57 @@
|
|||||||
/**
|
/**
|
||||||
* Graph visualization module for DNSRecon
|
* Graph visualization module for DNSRecon
|
||||||
* Handles network graph rendering using vis.js
|
* Handles network graph rendering using vis.js with proper large entity node hiding
|
||||||
*/
|
*/
|
||||||
|
const contextMenuCSS = `
|
||||||
|
.graph-context-menu {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 1000;
|
||||||
|
background: linear-gradient(135deg, #2a2a2a 0%, #1e1e1e 100%);
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 8px 25px rgba(0,0,0,0.6);
|
||||||
|
display: none;
|
||||||
|
font-family: 'Roboto Mono', monospace;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: #c7c7c7;
|
||||||
|
min-width: 180px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu ul {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu ul li {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu ul li:hover {
|
||||||
|
background: linear-gradient(135deg, #3a3a3a 0%, #2e2e2e 100%);
|
||||||
|
color: #00ff41;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu .menu-icon {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
width: 1.2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu ul li:first-child {
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.graph-context-menu ul li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
class GraphManager {
|
class GraphManager {
|
||||||
constructor(containerId) {
|
constructor(containerId) {
|
||||||
@ -12,6 +62,13 @@ class GraphManager {
|
|||||||
this.isInitialized = false;
|
this.isInitialized = false;
|
||||||
this.currentLayout = 'physics';
|
this.currentLayout = 'physics';
|
||||||
this.nodeInfoPopup = null;
|
this.nodeInfoPopup = null;
|
||||||
|
this.contextMenu = null;
|
||||||
|
this.history = [];
|
||||||
|
this.filterPanel = null;
|
||||||
|
this.trueRootIds = new Set();
|
||||||
|
// Track large entity members for proper hiding
|
||||||
|
this.largeEntityMembers = new Set();
|
||||||
|
this.isScanning = false;
|
||||||
|
|
||||||
this.options = {
|
this.options = {
|
||||||
nodes: {
|
nodes: {
|
||||||
@ -115,8 +172,14 @@ class GraphManager {
|
|||||||
randomSeed: 2
|
randomSeed: 2
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if (typeof document !== 'undefined') {
|
||||||
|
const style = document.createElement('style');
|
||||||
|
style.textContent = contextMenuCSS;
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
this.createNodeInfoPopup();
|
this.createNodeInfoPopup();
|
||||||
|
this.createContextMenu();
|
||||||
|
document.body.addEventListener('click', () => this.hideContextMenu());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -129,6 +192,30 @@ class GraphManager {
|
|||||||
document.body.appendChild(this.nodeInfoPopup);
|
document.body.appendChild(this.nodeInfoPopup);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create context menu
|
||||||
|
*/
|
||||||
|
createContextMenu() {
|
||||||
|
// Remove existing context menu if it exists
|
||||||
|
const existing = document.getElementById('graph-context-menu');
|
||||||
|
if (existing) {
|
||||||
|
existing.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.contextMenu = document.createElement('div');
|
||||||
|
this.contextMenu.id = 'graph-context-menu';
|
||||||
|
this.contextMenu.className = 'graph-context-menu';
|
||||||
|
this.contextMenu.style.display = 'none';
|
||||||
|
|
||||||
|
// Prevent body click listener from firing when clicking the menu itself
|
||||||
|
this.contextMenu.addEventListener('click', (event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.appendChild(this.contextMenu);
|
||||||
|
console.log('Context menu created and added to body');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the network graph
|
* Initialize the network graph
|
||||||
*/
|
*/
|
||||||
@ -155,6 +242,7 @@ class GraphManager {
|
|||||||
|
|
||||||
// Add graph controls
|
// Add graph controls
|
||||||
this.addGraphControls();
|
this.addGraphControls();
|
||||||
|
this.addFilterPanel();
|
||||||
|
|
||||||
console.log('Graph initialized successfully');
|
console.log('Graph initialized successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -173,6 +261,8 @@ class GraphManager {
|
|||||||
<button class="graph-control-btn" id="graph-fit" title="Fit to Screen">[FIT]</button>
|
<button class="graph-control-btn" id="graph-fit" title="Fit to Screen">[FIT]</button>
|
||||||
<button class="graph-control-btn" id="graph-physics" title="Toggle Physics">[PHYSICS]</button>
|
<button class="graph-control-btn" id="graph-physics" title="Toggle Physics">[PHYSICS]</button>
|
||||||
<button class="graph-control-btn" id="graph-cluster" title="Cluster Nodes">[CLUSTER]</button>
|
<button class="graph-control-btn" id="graph-cluster" title="Cluster Nodes">[CLUSTER]</button>
|
||||||
|
<button class="graph-control-btn" id="graph-unhide" title="Unhide All">[UNHIDE]</button>
|
||||||
|
<button class="graph-control-btn" id="graph-revert" title="Revert Last Action">[REVERT]</button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
this.container.appendChild(controlsContainer);
|
this.container.appendChild(controlsContainer);
|
||||||
@ -181,6 +271,14 @@ class GraphManager {
|
|||||||
document.getElementById('graph-fit').addEventListener('click', () => this.fitView());
|
document.getElementById('graph-fit').addEventListener('click', () => this.fitView());
|
||||||
document.getElementById('graph-physics').addEventListener('click', () => this.togglePhysics());
|
document.getElementById('graph-physics').addEventListener('click', () => this.togglePhysics());
|
||||||
document.getElementById('graph-cluster').addEventListener('click', () => this.toggleClustering());
|
document.getElementById('graph-cluster').addEventListener('click', () => this.toggleClustering());
|
||||||
|
document.getElementById('graph-unhide').addEventListener('click', () => this.unhideAll());
|
||||||
|
document.getElementById('graph-revert').addEventListener('click', () => this.revertLastAction());
|
||||||
|
}
|
||||||
|
|
||||||
|
addFilterPanel() {
|
||||||
|
this.filterPanel = document.createElement('div');
|
||||||
|
this.filterPanel.className = 'graph-filter-panel';
|
||||||
|
this.container.appendChild(this.filterPanel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -189,8 +287,31 @@ class GraphManager {
|
|||||||
setupNetworkEvents() {
|
setupNetworkEvents() {
|
||||||
if (!this.network) return;
|
if (!this.network) return;
|
||||||
|
|
||||||
|
// FIXED: Right-click context menu
|
||||||
|
this.container.addEventListener('contextmenu', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
console.log('Right-click detected at:', event.offsetX, event.offsetY);
|
||||||
|
|
||||||
|
// Get coordinates relative to the canvas
|
||||||
|
const pointer = {
|
||||||
|
x: event.offsetX,
|
||||||
|
y: event.offsetY
|
||||||
|
};
|
||||||
|
|
||||||
|
const nodeId = this.network.getNodeAt(pointer);
|
||||||
|
console.log('Node at pointer:', nodeId);
|
||||||
|
|
||||||
|
if (nodeId) {
|
||||||
|
// Pass the original client event for positioning
|
||||||
|
this.showContextMenu(nodeId, event);
|
||||||
|
} else {
|
||||||
|
this.hideContextMenu();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Node click event with details
|
// Node click event with details
|
||||||
this.network.on('click', (params) => {
|
this.network.on('click', (params) => {
|
||||||
|
this.hideContextMenu();
|
||||||
if (params.nodes.length > 0) {
|
if (params.nodes.length > 0) {
|
||||||
const nodeId = params.nodes[0];
|
const nodeId = params.nodes[0];
|
||||||
if (this.network.isCluster(nodeId)) {
|
if (this.network.isCluster(nodeId)) {
|
||||||
@ -216,10 +337,6 @@ class GraphManager {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.network.on('oncontext', (params) => {
|
|
||||||
params.event.preventDefault();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Stabilization events with progress
|
// Stabilization events with progress
|
||||||
this.network.on('stabilizationProgress', (params) => {
|
this.network.on('stabilizationProgress', (params) => {
|
||||||
const progress = params.iterations / params.total;
|
const progress = params.iterations / params.total;
|
||||||
@ -235,6 +352,13 @@ class GraphManager {
|
|||||||
console.log('Selected nodes:', params.nodes);
|
console.log('Selected nodes:', params.nodes);
|
||||||
console.log('Selected edges:', params.edges);
|
console.log('Selected edges:', params.edges);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Click away to hide context menu
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
if (!this.contextMenu.contains(e.target)) {
|
||||||
|
this.hideContextMenu();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -252,21 +376,28 @@ class GraphManager {
|
|||||||
this.initialize();
|
this.initialize();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.largeEntityMembers.clear();
|
||||||
const largeEntityMap = new Map();
|
const largeEntityMap = new Map();
|
||||||
|
|
||||||
graphData.nodes.forEach(node => {
|
graphData.nodes.forEach(node => {
|
||||||
if (node.type === 'large_entity' && node.attributes && Array.isArray(node.attributes.nodes)) {
|
if (node.type === 'large_entity' && node.attributes && Array.isArray(node.attributes.nodes)) {
|
||||||
node.attributes.nodes.forEach(nodeId => {
|
node.attributes.nodes.forEach(nodeId => {
|
||||||
largeEntityMap.set(nodeId, node.id);
|
largeEntityMap.set(nodeId, node.id);
|
||||||
|
this.largeEntityMembers.add(nodeId);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const processedNodes = graphData.nodes.map(node => {
|
const filteredNodes = graphData.nodes.filter(node => {
|
||||||
const processed = this.processNode(node);
|
// Only include nodes that are NOT members of large entities, but always include the container itself
|
||||||
if (largeEntityMap.has(node.id)) {
|
return !this.largeEntityMembers.has(node.id) || node.type === 'large_entity';
|
||||||
processed.hidden = true;
|
});
|
||||||
}
|
|
||||||
return processed;
|
console.log(`Filtered ${graphData.nodes.length - filteredNodes.length} large entity member nodes from visualization`);
|
||||||
|
|
||||||
|
// Process only the filtered nodes
|
||||||
|
const processedNodes = filteredNodes.map(node => {
|
||||||
|
return this.processNode(node);
|
||||||
});
|
});
|
||||||
|
|
||||||
const mergedEdges = {};
|
const mergedEdges = {};
|
||||||
@ -311,6 +442,11 @@ class GraphManager {
|
|||||||
this.nodes.update(processedNodes);
|
this.nodes.update(processedNodes);
|
||||||
this.edges.update(processedEdges);
|
this.edges.update(processedEdges);
|
||||||
|
|
||||||
|
// After data is loaded, compute roots and apply filters
|
||||||
|
this.computeTrueRoots();
|
||||||
|
this.updateFilterControls();
|
||||||
|
this.applyAllFilters();
|
||||||
|
|
||||||
// Highlight new additions briefly
|
// Highlight new additions briefly
|
||||||
if (newNodes.length > 0 || newEdges.length > 0) {
|
if (newNodes.length > 0 || newEdges.length > 0) {
|
||||||
setTimeout(() => this.highlightNewElements(newNodes, newEdges), 100);
|
setTimeout(() => this.highlightNewElements(newNodes, newEdges), 100);
|
||||||
@ -322,6 +458,8 @@ class GraphManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Graph updated: ${processedNodes.length} nodes, ${processedEdges.length} edges (${newNodes.length} new nodes, ${newEdges.length} new edges)`);
|
console.log(`Graph updated: ${processedNodes.length} nodes, ${processedEdges.length} edges (${newNodes.length} new nodes, ${newEdges.length} new edges)`);
|
||||||
|
console.log(`Large entity members hidden: ${this.largeEntityMembers.size}`);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to update graph:', error);
|
console.error('Failed to update graph:', error);
|
||||||
this.showError('Failed to update visualization');
|
this.showError('Failed to update visualization');
|
||||||
@ -408,8 +546,6 @@ class GraphManager {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return processedEdge;
|
return processedEdge;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -456,7 +592,6 @@ class GraphManager {
|
|||||||
return colors[nodeType] || '#ffffff';
|
return colors[nodeType] || '#ffffff';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get node border color based on type
|
* Get node border color based on type
|
||||||
* @param {string} nodeType - Node type
|
* @param {string} nodeType - Node type
|
||||||
@ -846,6 +981,8 @@ class GraphManager {
|
|||||||
clear() {
|
clear() {
|
||||||
this.nodes.clear();
|
this.nodes.clear();
|
||||||
this.edges.clear();
|
this.edges.clear();
|
||||||
|
this.history = [];
|
||||||
|
this.largeEntityMembers.clear(); // Clear large entity tracking
|
||||||
|
|
||||||
// Show placeholder
|
// Show placeholder
|
||||||
const placeholder = this.container.querySelector('.graph-placeholder');
|
const placeholder = this.container.querySelector('.graph-placeholder');
|
||||||
@ -866,59 +1003,590 @@ class GraphManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* * @param {Set} excludedNodeIds - Node IDs to exclude from analysis (for simulation)
|
||||||
|
* @param {Set} excludedEdgeTypes - Edge types to exclude from traversal
|
||||||
|
* @param {Set} excludedNodeTypes - Node types to exclude from traversal
|
||||||
|
* @returns {Object} Analysis results with reachable/unreachable nodes
|
||||||
|
*/
|
||||||
|
analyzeGraphReachability(excludedNodeIds = new Set(), excludedEdgeTypes = new Set(), excludedNodeTypes = new Set()) {
|
||||||
|
console.log("Performing comprehensive reachability analysis...");
|
||||||
|
|
||||||
|
const analysis = {
|
||||||
|
reachableNodes: new Set(),
|
||||||
|
unreachableNodes: new Set(),
|
||||||
|
isolatedClusters: [],
|
||||||
|
affectedNodes: new Set()
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.nodes.length === 0) return analysis;
|
||||||
|
|
||||||
|
// Build adjacency list excluding specified elements
|
||||||
|
const adjacencyList = {};
|
||||||
|
this.nodes.getIds().forEach(id => {
|
||||||
|
if (!excludedNodeIds.has(id)) {
|
||||||
|
adjacencyList[id] = [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.edges.forEach(edge => {
|
||||||
|
const edgeType = edge.metadata?.relationship_type || '';
|
||||||
|
if (!excludedEdgeTypes.has(edgeType) &&
|
||||||
|
!excludedNodeIds.has(edge.from) &&
|
||||||
|
!excludedNodeIds.has(edge.to)) {
|
||||||
|
|
||||||
|
if (adjacencyList[edge.from]) {
|
||||||
|
adjacencyList[edge.from].push(edge.to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// BFS traversal from true roots
|
||||||
|
const traversalQueue = [];
|
||||||
|
|
||||||
|
// Start from true roots that aren't excluded
|
||||||
|
this.trueRootIds.forEach(rootId => {
|
||||||
|
if (!excludedNodeIds.has(rootId)) {
|
||||||
|
const node = this.nodes.get(rootId);
|
||||||
|
if (node && !excludedNodeTypes.has(node.type)) {
|
||||||
|
if (!analysis.reachableNodes.has(rootId)) {
|
||||||
|
traversalQueue.push(rootId);
|
||||||
|
analysis.reachableNodes.add(rootId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// BFS to find all reachable nodes
|
||||||
|
let queueIndex = 0;
|
||||||
|
while (queueIndex < traversalQueue.length) {
|
||||||
|
const currentNode = traversalQueue[queueIndex++];
|
||||||
|
|
||||||
|
for (const neighbor of (adjacencyList[currentNode] || [])) {
|
||||||
|
if (!analysis.reachableNodes.has(neighbor)) {
|
||||||
|
const node = this.nodes.get(neighbor);
|
||||||
|
if (node && !excludedNodeTypes.has(node.type)) {
|
||||||
|
analysis.reachableNodes.add(neighbor);
|
||||||
|
traversalQueue.push(neighbor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identify unreachable nodes (maintaining forensic integrity)
|
||||||
|
Object.keys(adjacencyList).forEach(nodeId => {
|
||||||
|
if (!analysis.reachableNodes.has(nodeId)) {
|
||||||
|
analysis.unreachableNodes.add(nodeId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Find isolated clusters among unreachable nodes
|
||||||
|
analysis.isolatedClusters = this.findIsolatedClusters(
|
||||||
|
Array.from(analysis.unreachableNodes),
|
||||||
|
adjacencyList
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(`Reachability analysis complete:`, {
|
||||||
|
reachable: analysis.reachableNodes.size,
|
||||||
|
unreachable: analysis.unreachableNodes.size,
|
||||||
|
clusters: analysis.isolatedClusters.length
|
||||||
|
});
|
||||||
|
|
||||||
|
return analysis;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get network statistics
|
* Find isolated clusters within a set of nodes
|
||||||
* @returns {Object} Statistics object
|
* Used for forensic analysis to identify disconnected subgraphs
|
||||||
|
*/
|
||||||
|
findIsolatedClusters(nodeIds, adjacencyList) {
|
||||||
|
const visited = new Set();
|
||||||
|
const clusters = [];
|
||||||
|
|
||||||
|
for (const nodeId of nodeIds) {
|
||||||
|
if (!visited.has(nodeId)) {
|
||||||
|
const cluster = [];
|
||||||
|
const stack = [nodeId];
|
||||||
|
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const current = stack.pop();
|
||||||
|
if (!visited.has(current)) {
|
||||||
|
visited.add(current);
|
||||||
|
cluster.push(current);
|
||||||
|
|
||||||
|
// Add unvisited neighbors within the unreachable set
|
||||||
|
for (const neighbor of (adjacencyList[current] || [])) {
|
||||||
|
if (nodeIds.includes(neighbor) && !visited.has(neighbor)) {
|
||||||
|
stack.push(neighbor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cluster.length > 0) {
|
||||||
|
clusters.push(cluster);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return clusters;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ENHANCED: Get comprehensive graph statistics with forensic information
|
||||||
|
* Updates the existing getStatistics() method
|
||||||
*/
|
*/
|
||||||
getStatistics() {
|
getStatistics() {
|
||||||
return {
|
const basicStats = {
|
||||||
nodeCount: this.nodes.length,
|
nodeCount: this.nodes.length,
|
||||||
edgeCount: this.edges.length,
|
edgeCount: this.edges.length,
|
||||||
//isStabilized: this.network ? this.network.isStabilized() : false
|
largeEntityMembersHidden: this.largeEntityMembers.size
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add forensic statistics
|
||||||
|
const visibleNodes = this.nodes.get({ filter: node => !node.hidden });
|
||||||
|
const hiddenNodes = this.nodes.get({ filter: node => node.hidden });
|
||||||
|
|
||||||
|
return {
|
||||||
|
...basicStats,
|
||||||
|
forensicStatistics: {
|
||||||
|
visibleNodes: visibleNodes.length,
|
||||||
|
hiddenNodes: hiddenNodes.length,
|
||||||
|
trueRoots: this.trueRootIds.size,
|
||||||
|
integrityStatus: visibleNodes.length > 0 && this.trueRootIds.size > 0 ? 'INTACT' : 'COMPROMISED'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
computeTrueRoots() {
|
||||||
|
this.trueRootIds.clear();
|
||||||
|
const allNodes = this.nodes.get({ returnType: 'Object' });
|
||||||
|
const allEdges = this.edges.get();
|
||||||
|
const inDegrees = {};
|
||||||
|
|
||||||
|
for (const nodeId in allNodes) {
|
||||||
|
inDegrees[nodeId] = 0;
|
||||||
|
}
|
||||||
|
allEdges.forEach(edge => {
|
||||||
|
if (inDegrees[edge.to] !== undefined) {
|
||||||
|
inDegrees[edge.to]++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const nodeId in allNodes) {
|
||||||
|
if (inDegrees[nodeId] === 0) {
|
||||||
|
this.trueRootIds.add(nodeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log("Computed true roots:", this.trueRootIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateFilterControls() {
|
||||||
|
if (!this.filterPanel) return;
|
||||||
|
const nodeTypes = new Set(this.nodes.get().map(n => n.type));
|
||||||
|
const edgeTypes = new Set(this.edges.get().map(e => e.metadata.relationship_type));
|
||||||
|
|
||||||
|
// Wrap both columns in a single container with vertical layout
|
||||||
|
let filterHTML = '<div class="filter-container">';
|
||||||
|
|
||||||
|
// Nodes section
|
||||||
|
filterHTML += '<div class="filter-column"><h4>Nodes</h4><div class="checkbox-group">';
|
||||||
|
nodeTypes.forEach(type => {
|
||||||
|
const label = type === 'correlation_object' ? 'latent correlations' : type;
|
||||||
|
const isChecked = type !== 'correlation_object';
|
||||||
|
filterHTML += `<label><input type="checkbox" data-filter-type="node" value="${type}" ${isChecked ? 'checked' : ''}> ${label}</label>`;
|
||||||
|
});
|
||||||
|
filterHTML += '</div></div>';
|
||||||
|
|
||||||
|
// Edges section
|
||||||
|
filterHTML += '<div class="filter-column"><h4>Edges</h4><div class="checkbox-group">';
|
||||||
|
edgeTypes.forEach(type => {
|
||||||
|
filterHTML += `<label><input type="checkbox" data-filter-type="edge" value="${type}" checked> ${type}</label>`;
|
||||||
|
});
|
||||||
|
filterHTML += '</div></div>';
|
||||||
|
|
||||||
|
filterHTML += '</div>'; // Close filter-container
|
||||||
|
this.filterPanel.innerHTML = filterHTML;
|
||||||
|
|
||||||
|
this.filterPanel.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
|
||||||
|
checkbox.addEventListener('change', () => this.applyAllFilters());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ENHANCED: Apply filters using consolidated reachability analysis
|
||||||
|
* Replaces the existing applyAllFilters() method
|
||||||
|
*/
|
||||||
|
applyAllFilters() {
|
||||||
|
console.log("Applying filters with enhanced reachability analysis...");
|
||||||
|
if (this.nodes.length === 0) return;
|
||||||
|
|
||||||
|
// Get filter criteria from UI
|
||||||
|
const excludedNodeTypes = new Set();
|
||||||
|
this.filterPanel?.querySelectorAll('input[data-filter-type="node"]:not(:checked)').forEach(cb => {
|
||||||
|
excludedNodeTypes.add(cb.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
const excludedEdgeTypes = new Set();
|
||||||
|
this.filterPanel?.querySelectorAll('input[data-filter-type="edge"]:not(:checked)').forEach(cb => {
|
||||||
|
excludedEdgeTypes.add(cb.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Perform comprehensive analysis
|
||||||
|
const analysis = this.analyzeGraphReachability(new Set(), excludedEdgeTypes, excludedNodeTypes);
|
||||||
|
|
||||||
|
// Apply visibility updates
|
||||||
|
const nodeUpdates = this.nodes.map(node => ({
|
||||||
|
id: node.id,
|
||||||
|
hidden: !analysis.reachableNodes.has(node.id)
|
||||||
|
}));
|
||||||
|
|
||||||
|
const edgeUpdates = this.edges.map(edge => ({
|
||||||
|
id: edge.id,
|
||||||
|
hidden: excludedEdgeTypes.has(edge.metadata?.relationship_type || '') ||
|
||||||
|
!analysis.reachableNodes.has(edge.from) ||
|
||||||
|
!analysis.reachableNodes.has(edge.to)
|
||||||
|
}));
|
||||||
|
|
||||||
|
this.nodes.update(nodeUpdates);
|
||||||
|
this.edges.update(edgeUpdates);
|
||||||
|
|
||||||
|
console.log(`Enhanced filters applied. Visible nodes: ${analysis.reachableNodes.size}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ENHANCED: Hide node with forensic integrity using reachability analysis
|
||||||
|
* Replaces the existing hideNodeAndOrphans() method
|
||||||
|
*/
|
||||||
|
hideNodeWithReachabilityAnalysis(nodeId) {
|
||||||
|
console.log(`Hiding node ${nodeId} with reachability analysis...`);
|
||||||
|
|
||||||
|
// Simulate hiding this node and analyze impact
|
||||||
|
const excludedNodes = new Set([nodeId]);
|
||||||
|
const analysis = this.analyzeGraphReachability(excludedNodes);
|
||||||
|
|
||||||
|
// Nodes that will become unreachable (should be hidden)
|
||||||
|
const nodesToHide = [nodeId, ...Array.from(analysis.unreachableNodes)];
|
||||||
|
|
||||||
|
// Store history for potential revert
|
||||||
|
const historyData = {
|
||||||
|
nodeIds: nodesToHide,
|
||||||
|
operation: 'hide_with_reachability',
|
||||||
|
timestamp: Date.now()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Apply hiding with forensic documentation
|
||||||
|
const updates = nodesToHide.map(id => ({
|
||||||
|
id: id,
|
||||||
|
hidden: true,
|
||||||
|
forensicNote: `Hidden due to reachability analysis from ${nodeId}`
|
||||||
|
}));
|
||||||
|
|
||||||
|
this.nodes.update(updates);
|
||||||
|
this.addToHistory('hide', historyData);
|
||||||
|
|
||||||
|
console.log(`Forensic hide operation: ${nodesToHide.length} nodes hidden`, {
|
||||||
|
originalTarget: nodeId,
|
||||||
|
cascadeNodes: nodesToHide.length - 1,
|
||||||
|
isolatedClusters: analysis.isolatedClusters.length
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
hiddenNodes: nodesToHide,
|
||||||
|
isolatedClusters: analysis.isolatedClusters
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply filters to the graph
|
* ENHANCED: Delete node with forensic integrity using reachability analysis
|
||||||
* @param {string} nodeType - The type of node to show ('all' for no filter)
|
* Replaces the existing deleteNodeAndOrphans() method
|
||||||
* @param {number} minConfidence - The minimum confidence score for edges to be visible
|
|
||||||
*/
|
*/
|
||||||
applyFilters(nodeType, minConfidence) {
|
async deleteNodeWithReachabilityAnalysis(nodeId) {
|
||||||
console.log(`Applying filters: nodeType=${nodeType}, minConfidence=${minConfidence}`);
|
console.log(`Deleting node ${nodeId} with reachability analysis...`);
|
||||||
|
|
||||||
const nodeUpdates = [];
|
// Simulate deletion and analyze impact
|
||||||
const edgeUpdates = [];
|
const excludedNodes = new Set([nodeId]);
|
||||||
|
const analysis = this.analyzeGraphReachability(excludedNodes);
|
||||||
|
|
||||||
const allNodes = this.nodes.get({ returnType: 'Object' });
|
// Nodes that will become unreachable (should be deleted)
|
||||||
const allEdges = this.edges.get();
|
const nodesToDelete = [nodeId, ...Array.from(analysis.unreachableNodes)];
|
||||||
|
|
||||||
// Determine which nodes are visible based on the nodeType filter
|
// Collect forensic data before deletion
|
||||||
for (const nodeId in allNodes) {
|
const historyData = {
|
||||||
const node = allNodes[nodeId];
|
nodes: nodesToDelete.map(id => this.nodes.get(id)).filter(Boolean),
|
||||||
const isVisible = (nodeType === 'all' || node.type === nodeType);
|
edges: [],
|
||||||
nodeUpdates.push({ id: nodeId, hidden: !isVisible });
|
operation: 'delete_with_reachability',
|
||||||
|
timestamp: Date.now(),
|
||||||
|
forensicAnalysis: {
|
||||||
|
originalTarget: nodeId,
|
||||||
|
cascadeNodes: nodesToDelete.length - 1,
|
||||||
|
isolatedClusters: analysis.isolatedClusters.length,
|
||||||
|
clusterSizes: analysis.isolatedClusters.map(cluster => cluster.length)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Collect affected edges
|
||||||
|
nodesToDelete.forEach(id => {
|
||||||
|
const connectedEdgeIds = this.network.getConnectedEdges(id);
|
||||||
|
const edges = this.edges.get(connectedEdgeIds);
|
||||||
|
historyData.edges.push(...edges);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove duplicates from edges
|
||||||
|
historyData.edges = Array.from(new Map(historyData.edges.map(e => [e.id, e])).values());
|
||||||
|
|
||||||
|
// Perform backend deletion with forensic logging
|
||||||
|
let operationFailed = false;
|
||||||
|
|
||||||
|
for (const targetNodeId of nodesToDelete) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/graph/node/${targetNodeId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
forensicContext: {
|
||||||
|
operation: 'reachability_cascade_delete',
|
||||||
|
originalTarget: nodeId,
|
||||||
|
analysisTimestamp: historyData.timestamp
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
if (!result.success) {
|
||||||
|
console.error(`Backend deletion failed for node ${targetNodeId}:`, result.error);
|
||||||
|
operationFailed = true;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update nodes first to determine edge visibility
|
console.log(`Node ${targetNodeId} deleted from backend with forensic context`);
|
||||||
this.nodes.update(nodeUpdates);
|
this.nodes.remove({ id: targetNodeId });
|
||||||
|
|
||||||
// Determine which edges are visible based on confidence and connected nodes
|
} catch (error) {
|
||||||
for (const edge of allEdges) {
|
console.error(`API error during deletion of node ${targetNodeId}:`, error);
|
||||||
const sourceNode = this.nodes.get(edge.from);
|
operationFailed = true;
|
||||||
const targetNode = this.nodes.get(edge.to);
|
break;
|
||||||
const confidence = edge.metadata ? edge.metadata.confidence_score : 0;
|
}
|
||||||
|
|
||||||
const isVisible = confidence >= minConfidence &&
|
|
||||||
sourceNode && !sourceNode.hidden &&
|
|
||||||
targetNode && !targetNode.hidden;
|
|
||||||
|
|
||||||
edgeUpdates.push({ id: edge.id, hidden: !isVisible });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.edges.update(edgeUpdates);
|
// Handle operation results
|
||||||
|
if (!operationFailed) {
|
||||||
|
this.addToHistory('delete', historyData);
|
||||||
|
console.log(`Forensic delete operation completed:`, historyData.forensicAnalysis);
|
||||||
|
|
||||||
console.log('Filters applied.');
|
return {
|
||||||
|
success: true,
|
||||||
|
deletedNodes: nodesToDelete,
|
||||||
|
forensicAnalysis: historyData.forensicAnalysis
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// Revert UI changes if backend operations failed - use update instead of add
|
||||||
|
console.log("Reverting UI changes due to backend failure");
|
||||||
|
this.nodes.update(historyData.nodes);
|
||||||
|
this.edges.update(historyData.edges);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Backend deletion failed, UI reverted"
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show context menu for a node
|
||||||
|
* @param {string} nodeId - The ID of the node
|
||||||
|
* @param {Event} event - The contextmenu event
|
||||||
|
*/
|
||||||
|
showContextMenu(nodeId, event) {
|
||||||
|
console.log('Showing context menu for node:', nodeId);
|
||||||
|
const node = this.nodes.get(nodeId);
|
||||||
|
|
||||||
|
// Create menu items
|
||||||
|
let menuItems = `
|
||||||
|
<ul>
|
||||||
|
<li data-action="focus" data-node-id="${nodeId}">
|
||||||
|
<span class="menu-icon">🎯</span>
|
||||||
|
<span>Focus on Node</span>
|
||||||
|
</li>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Add "Iterate Scan" option only for domain or IP nodes
|
||||||
|
if (node && (node.type === 'domain' || node.type === 'ip')) {
|
||||||
|
const disabled = this.isScanning ? 'disabled' : ''; // Check if scanning
|
||||||
|
const title = this.isScanning ? 'A scan is already in progress' : 'Iterate Scan (Add to Graph)'; // Add a title for disabled state
|
||||||
|
menuItems += `
|
||||||
|
<li data-action="iterate" data-node-id="${nodeId}" ${disabled} title="${title}">
|
||||||
|
<span class="menu-icon">➕</span>
|
||||||
|
<span>Iterate Scan (Add to Graph)</span>
|
||||||
|
</li>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
menuItems += `
|
||||||
|
<li data-action="hide" data-node-id="${nodeId}">
|
||||||
|
<span class="menu-icon">👁️🗨️</span>
|
||||||
|
<span>Hide Node</span>
|
||||||
|
</li>
|
||||||
|
<li data-action="delete" data-node-id="${nodeId}">
|
||||||
|
<span class="menu-icon">🗑️</span>
|
||||||
|
<span>Delete Node</span>
|
||||||
|
</li>
|
||||||
|
<li data-action="details" data-node-id="${nodeId}">
|
||||||
|
<span class="menu-icon">ℹ️</span>
|
||||||
|
<span>Show Details</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
`;
|
||||||
|
|
||||||
|
this.contextMenu.innerHTML = menuItems;
|
||||||
|
|
||||||
|
// Position the menu
|
||||||
|
this.contextMenu.style.left = `${event.clientX}px`;
|
||||||
|
this.contextMenu.style.top = `${event.clientY}px`;
|
||||||
|
this.contextMenu.style.display = 'block';
|
||||||
|
|
||||||
|
// Ensure menu stays within viewport
|
||||||
|
const rect = this.contextMenu.getBoundingClientRect();
|
||||||
|
if (rect.right > window.innerWidth) {
|
||||||
|
this.contextMenu.style.left = `${event.clientX - rect.width}px`;
|
||||||
|
}
|
||||||
|
if (rect.bottom > window.innerHeight) {
|
||||||
|
this.contextMenu.style.top = `${event.clientY - rect.height}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add event listeners to menu items
|
||||||
|
this.contextMenu.querySelectorAll('li').forEach(item => {
|
||||||
|
item.addEventListener('click', (e) => {
|
||||||
|
if (e.currentTarget.hasAttribute('disabled')) { // Prevent action if disabled
|
||||||
|
e.stopPropagation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
e.stopPropagation();
|
||||||
|
const action = e.currentTarget.dataset.action;
|
||||||
|
const nodeId = e.currentTarget.dataset.nodeId;
|
||||||
|
console.log('Context menu action:', action, 'for node:', nodeId);
|
||||||
|
this.performContextMenuAction(action, nodeId);
|
||||||
|
this.hideContextMenu();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide the context menu
|
||||||
|
*/
|
||||||
|
hideContextMenu() {
|
||||||
|
if (this.contextMenu) {
|
||||||
|
this.contextMenu.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UPDATED: Enhanced context menu actions using new methods
|
||||||
|
* Updates the existing performContextMenuAction() method
|
||||||
|
*/
|
||||||
|
performContextMenuAction(action, nodeId) {
|
||||||
|
console.log('Performing enhanced action:', action, 'on node:', nodeId);
|
||||||
|
|
||||||
|
switch (action) {
|
||||||
|
case 'focus':
|
||||||
|
this.focusOnNode(nodeId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'iterate':
|
||||||
|
const event = new CustomEvent('iterateScan', {
|
||||||
|
detail: { nodeId }
|
||||||
|
});
|
||||||
|
document.dispatchEvent(event);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'hide':
|
||||||
|
// Use enhanced method with reachability analysis
|
||||||
|
this.hideNodeWithReachabilityAnalysis(nodeId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'delete':
|
||||||
|
// Use enhanced method with reachability analysis
|
||||||
|
this.deleteNodeWithReachabilityAnalysis(nodeId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'details':
|
||||||
|
const node = this.nodes.get(nodeId);
|
||||||
|
if (node) {
|
||||||
|
this.showNodeDetails(node);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.warn('Unknown action:', action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an operation to the history stack
|
||||||
|
* @param {string} type - The type of operation ('hide', 'delete')
|
||||||
|
* @param {Object} data - The data needed to revert the operation
|
||||||
|
*/
|
||||||
|
addToHistory(type, data) {
|
||||||
|
this.history.push({ type, data });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revert the last action
|
||||||
|
*/
|
||||||
|
async revertLastAction() {
|
||||||
|
const lastAction = this.history.pop();
|
||||||
|
if (!lastAction) {
|
||||||
|
console.log('No actions to revert.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (lastAction.type) {
|
||||||
|
case 'hide':
|
||||||
|
// Revert hiding nodes by un-hiding them
|
||||||
|
const updates = lastAction.data.nodeIds.map(id => ({ id: id, hidden: false }));
|
||||||
|
this.nodes.update(updates);
|
||||||
|
break;
|
||||||
|
case 'delete':
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/graph/revert', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(lastAction)
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
console.log('Delete action reverted successfully on backend.');
|
||||||
|
// Re-add all nodes and edges from the history to the local view - use update instead of add
|
||||||
|
this.nodes.update(lastAction.data.nodes);
|
||||||
|
this.edges.update(lastAction.data.edges);
|
||||||
|
} else {
|
||||||
|
console.error('Failed to revert delete action on backend:', result.error);
|
||||||
|
// Push the action back onto the history stack if the API call failed
|
||||||
|
this.history.push(lastAction);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error during revert API call:', error);
|
||||||
|
this.history.push(lastAction);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unhide all hidden nodes
|
||||||
|
*/
|
||||||
|
unhideAll() {
|
||||||
|
const allNodes = this.nodes.get({
|
||||||
|
filter: (node) => node.hidden === true
|
||||||
|
});
|
||||||
|
const updates = allNodes.map(node => ({ id: node.id, hidden: false }));
|
||||||
|
this.nodes.update(updates);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export for use in main.js
|
// Export for use in main.js
|
||||||
|
1390
static/js/main.js
1390
static/js/main.js
File diff suppressed because it is too large
Load Diff
@ -32,19 +32,8 @@
|
|||||||
|
|
||||||
<div class="form-container">
|
<div class="form-container">
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label for="target-domain">Target Domain</label>
|
<label for="target-input">Target Domain or IP</label>
|
||||||
<input type="text" id="target-domain" placeholder="example.com" autocomplete="off">
|
<input type="text" id="target-input" placeholder="example.com or 8.8.8.8" autocomplete="off">
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="input-group">
|
|
||||||
<label for="max-depth">Recursion Depth</label>
|
|
||||||
<select id="max-depth">
|
|
||||||
<option value="1">Depth 1 - Direct relationships</option>
|
|
||||||
<option value="2" selected>Depth 2 - Recommended</option>
|
|
||||||
<option value="3">Depth 3 - Extended analysis</option>
|
|
||||||
<option value="4">Depth 4 - Deep reconnaissance</option>
|
|
||||||
<option value="5">Depth 5 - Maximum depth</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="button-group">
|
<div class="button-group">
|
||||||
@ -64,9 +53,9 @@
|
|||||||
<span class="btn-icon">[EXPORT]</span>
|
<span class="btn-icon">[EXPORT]</span>
|
||||||
<span>Download Results</span>
|
<span>Download Results</span>
|
||||||
</button>
|
</button>
|
||||||
<button id="configure-api-keys" class="btn btn-secondary">
|
<button id="configure-settings" class="btn btn-secondary">
|
||||||
<span class="btn-icon">[API]</span>
|
<span class="btn-icon">[API]</span>
|
||||||
<span>Configure API Keys</span>
|
<span>Settings</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -104,30 +93,22 @@
|
|||||||
<div class="progress-bar">
|
<div class="progress-bar">
|
||||||
<div id="progress-fill" class="progress-fill"></div>
|
<div id="progress-fill" class="progress-fill"></div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="progress-placeholder">
|
||||||
|
<span class="status-label">
|
||||||
|
⚠️ <strong>Important:</strong> Scanning large public services (e.g., Google, Cloudflare, AWS) is
|
||||||
|
<strong>discouraged</strong> due to rate limits (e.g., crt.sh).
|
||||||
|
<br><br>
|
||||||
|
Our task scheduler operates on a <strong>priority-based queue</strong>:
|
||||||
|
Short, targeted tasks like DNS are processed first, while resource-intensive requests (e.g., crt.sh)
|
||||||
|
are <strong>automatically deprioritized</strong> and may be processed later.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="visualization-panel">
|
<section class="visualization-panel">
|
||||||
<div class="panel-header">
|
<div class="panel-header">
|
||||||
<h2>Infrastructure Map</h2>
|
<h2>Infrastructure Map</h2>
|
||||||
<div class="view-controls">
|
|
||||||
<div class="filter-group">
|
|
||||||
<label for="node-type-filter">Node Type:</label>
|
|
||||||
<select id="node-type-filter">
|
|
||||||
<option value="all">All</option>
|
|
||||||
<option value="domain">Domain</option>
|
|
||||||
<option value="ip">IP</option>
|
|
||||||
<option value="asn">ASN</option>
|
|
||||||
<option value="correlation_object">Correlation Object</option>
|
|
||||||
<option value="large_entity">Large Entity</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="filter-group">
|
|
||||||
<label for="confidence-filter">Min Confidence:</label>
|
|
||||||
<input type="range" id="confidence-filter" min="0" max="1" step="0.1" value="0">
|
|
||||||
<span id="confidence-value">0</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="network-graph" class="graph-container">
|
<div id="network-graph" class="graph-container">
|
||||||
@ -205,16 +186,28 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="api-key-modal" class="modal">
|
<div id="settings-modal" class="modal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h3>Configure API Keys</h3>
|
<h3>Settings</h3>
|
||||||
<button id="api-key-modal-close" class="modal-close">[×]</button>
|
<button id="settings-modal-close" class="modal-close">[×]</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<p class="modal-description">
|
<p class="modal-description">
|
||||||
Enter your API keys for enhanced data providers. Keys are stored in memory for the current session only and are never saved to disk.
|
Configure scan settings and API keys. Keys are stored in memory for the current session only.
|
||||||
|
Only provide API-keys you dont use for anything else. Don´t enter an API-key if you don´t trust me (best practice would that you don´t).
|
||||||
</p>
|
</p>
|
||||||
|
<br>
|
||||||
|
<div class="input-group">
|
||||||
|
<label for="max-depth">Recursion Depth</label>
|
||||||
|
<select id="max-depth">
|
||||||
|
<option value="1">Depth 1 - Direct relationships</option>
|
||||||
|
<option value="2" selected>Depth 2 - Recommended</option>
|
||||||
|
<option value="3">Depth 3 - Extended analysis</option>
|
||||||
|
<option value="4">Depth 4 - Deep reconnaissance</option>
|
||||||
|
<option value="5">Depth 5 - Maximum depth</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
<div id="api-key-inputs">
|
<div id="api-key-inputs">
|
||||||
</div>
|
</div>
|
||||||
<div class="button-group" style="flex-direction: row; justify-content: flex-end;">
|
<div class="button-group" style="flex-direction: row; justify-content: flex-end;">
|
||||||
@ -222,7 +215,7 @@
|
|||||||
<span>Reset</span>
|
<span>Reset</span>
|
||||||
</button>
|
</button>
|
||||||
<button id="save-api-keys" class="btn btn-primary">
|
<button id="save-api-keys" class="btn btn-primary">
|
||||||
<span>Save Keys</span>
|
<span>Save API-Keys</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -48,3 +48,15 @@ def _is_valid_ip(ip: str) -> bool:
|
|||||||
|
|
||||||
except (ValueError, AttributeError):
|
except (ValueError, AttributeError):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def is_valid_target(target: str) -> bool:
|
||||||
|
"""
|
||||||
|
Checks if the target is a valid domain or IP address.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
target: The target string to validate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if the target is a valid domain or IP, False otherwise.
|
||||||
|
"""
|
||||||
|
return _is_valid_domain(target) or _is_valid_ip(target)
|
Loading…
x
Reference in New Issue
Block a user