-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
339 lines (270 loc) · 10.8 KB
/
config.py
File metadata and controls
339 lines (270 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/usr/bin/env python3
"""
ShadowHunter — Centralized Configuration Management
Loads configuration from environment variables with sensible defaults.
Use .env file for local development.
"""
import os
from pathlib import Path
from typing import Optional, List
from dataclasses import dataclass, field
from functools import lru_cache
# Try to load .env file if python-dotenv is available
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
# ============================================================================
# CONFIGURATION CLASSES
# ============================================================================
@dataclass
class LogConfig:
"""Logging configuration."""
level: str = "info"
dir: Path = Path("logs")
enable_console: bool = True
enable_file: bool = True
enable_json: bool = True
max_file_size: int = 10 * 1024 * 1024 # 10 MB
backup_count: int = 5
@dataclass
class DatabaseConfig:
"""Database configuration."""
# Neo4j
neo4j_uri: str = "bolt://localhost:7687"
neo4j_user: str = "neo4j"
neo4j_password: str = ""
# Redis
redis_url: str = "redis://localhost:6379"
@dataclass
class ThreatIntelConfig:
"""Threat intelligence API configuration."""
# HaveIBeenPwned
hibp_api_key: Optional[str] = None
# VirusTotal
virustotal_api_key: Optional[str] = None
virustotal_rate_limit: int = 4 # requests per minute (free tier)
# Shodan
shodan_api_key: Optional[str] = None
# AbuseIPDB
abuseipdb_api_key: Optional[str] = None
abuseipdb_rate_limit: int = 1000 # requests per day
@dataclass
class BlockchainConfig:
"""Blockchain forensics configuration."""
bubblemaps_api_key: Optional[str] = None
solana_rpc_url: str = "https://api.mainnet-beta.solana.com"
helius_api_key: Optional[str] = None
etherscan_api_key: Optional[str] = None
blockchain_com_api_key: Optional[str] = None
@dataclass
class TorConfig:
"""Tor network configuration."""
proxy_host: str = "127.0.0.1"
proxy_port: int = 9050
control_port: int = 9051
password: Optional[str] = None
@dataclass
class TelegramConfig:
"""Telegram integration configuration."""
api_id: Optional[int] = None
api_hash: Optional[str] = None
phone: Optional[str] = None
@dataclass
class EmailConfig:
"""Email alerting configuration."""
smtp_host: str = "smtp.gmail.com"
smtp_port: int = 587
smtp_user: Optional[str] = None
smtp_password: Optional[str] = None
from_address: str = "noreply@shadowhunter.local"
alert_recipients: List[str] = field(default_factory=list)
@dataclass
class GoogleConfig:
"""Google API configuration for dorking."""
api_key: Optional[str] = None
cse_id: Optional[str] = None
@dataclass
class APIConfig:
"""API server configuration."""
host: str = "0.0.0.0"
port: int = 8000
reload: bool = False
# JWT
jwt_secret_key: str = "change-this-in-production"
jwt_algorithm: str = "HS256"
jwt_expire_minutes: int = 30
@dataclass
class GitHubConfig:
"""GitHub configuration for secret scanning."""
token: Optional[str] = None
# ============================================================================
# MAIN CONFIG CLASS
# ============================================================================
@dataclass
class ShadowHunterConfig:
"""
Main configuration container.
All settings are loaded from environment variables with sensible defaults.
Usage:
config = get_config()
print(config.log.level)
print(config.threat_intel.virustotal_api_key)
"""
log: LogConfig = field(default_factory=LogConfig)
database: DatabaseConfig = field(default_factory=DatabaseConfig)
threat_intel: ThreatIntelConfig = field(default_factory=ThreatIntelConfig)
blockchain: BlockchainConfig = field(default_factory=BlockchainConfig)
tor: TorConfig = field(default_factory=TorConfig)
telegram: TelegramConfig = field(default_factory=TelegramConfig)
email: EmailConfig = field(default_factory=EmailConfig)
google: GoogleConfig = field(default_factory=GoogleConfig)
api: APIConfig = field(default_factory=APIConfig)
github: GitHubConfig = field(default_factory=GitHubConfig)
def _load_config_from_env() -> ShadowHunterConfig:
"""
Load configuration from environment variables.
Environment variables take precedence over defaults.
"""
def get_env(key: str, default: str = "") -> str:
return os.environ.get(key, default)
def get_env_int(key: str, default: int) -> int:
val = os.environ.get(key)
return int(val) if val else default
def get_env_bool(key: str, default: bool) -> bool:
val = os.environ.get(key, "").lower()
if val in ("true", "1", "yes"):
return True
if val in ("false", "0", "no"):
return False
return default
def get_env_list(key: str, default: List[str] = None) -> List[str]:
val = os.environ.get(key, "")
if val:
return [x.strip() for x in val.split(",") if x.strip()]
return default or []
return ShadowHunterConfig(
log=LogConfig(
level=get_env("LOG_LEVEL", "info"),
dir=Path(get_env("LOG_DIR", "logs")),
),
database=DatabaseConfig(
neo4j_uri=get_env("NEO4J_URI", "bolt://localhost:7687"),
neo4j_user=get_env("NEO4J_USER", "neo4j"),
neo4j_password=get_env("NEO4J_PASSWORD", ""),
redis_url=get_env("REDIS_URL", "redis://localhost:6379"),
),
threat_intel=ThreatIntelConfig(
hibp_api_key=get_env("HIBP_API_KEY") or None,
virustotal_api_key=get_env("VIRUSTOTAL_API_KEY") or None,
shodan_api_key=get_env("SHODAN_API_KEY") or None,
abuseipdb_api_key=get_env("ABUSEIPDB_API_KEY") or None,
),
blockchain=BlockchainConfig(
bubblemaps_api_key=get_env("BUBBLEMAPS_API_KEY") or None,
solana_rpc_url=get_env("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com"),
helius_api_key=get_env("HELIUS_API_KEY") or None,
etherscan_api_key=get_env("ETHERSCAN_API_KEY") or None,
blockchain_com_api_key=get_env("BLOCKCHAIN_COM_API_KEY") or None,
),
tor=TorConfig(
proxy_host=get_env("TOR_PROXY_HOST", "127.0.0.1"),
proxy_port=get_env_int("TOR_PROXY_PORT", 9050),
control_port=get_env_int("TOR_CONTROL_PORT", 9051),
password=get_env("TOR_PASSWORD") or None,
),
telegram=TelegramConfig(
api_id=get_env_int("TELEGRAM_API_ID", 0) or None,
api_hash=get_env("TELEGRAM_API_HASH") or None,
phone=get_env("TELEGRAM_PHONE") or None,
),
email=EmailConfig(
smtp_host=get_env("SMTP_HOST", "smtp.gmail.com"),
smtp_port=get_env_int("SMTP_PORT", 587),
smtp_user=get_env("SMTP_USER") or None,
smtp_password=get_env("SMTP_PASSWORD") or None,
from_address=get_env("SMTP_FROM", "noreply@shadowhunter.local"),
alert_recipients=get_env_list("ALERT_EMAILS"),
),
google=GoogleConfig(
api_key=get_env("GOOGLE_API_KEY") or None,
cse_id=get_env("GOOGLE_CSE_ID") or None,
),
api=APIConfig(
host=get_env("API_HOST", "0.0.0.0"),
port=get_env_int("API_PORT", 8000),
reload=get_env_bool("API_RELOAD", False),
jwt_secret_key=get_env("JWT_SECRET_KEY", "change-this-in-production"),
jwt_algorithm=get_env("JWT_ALGORITHM", "HS256"),
jwt_expire_minutes=get_env_int("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", 30),
),
github=GitHubConfig(
token=get_env("GITHUB_TOKEN") or None,
),
)
@lru_cache()
def get_config() -> ShadowHunterConfig:
"""
Get cached configuration singleton.
Configuration is loaded once and cached for performance.
Usage:
from config import get_config
config = get_config()
print(config.log.level)
"""
return _load_config_from_env()
# ============================================================================
# VALIDATION
# ============================================================================
def validate_config(config: ShadowHunterConfig) -> List[str]:
"""
Validate configuration and return list of warnings.
Returns:
List of warning messages for missing/invalid config
"""
warnings = []
# Check critical API keys
if not config.threat_intel.virustotal_api_key:
warnings.append("VIRUSTOTAL_API_KEY not set — IOC enrichment will be limited")
if not config.threat_intel.shodan_api_key:
warnings.append("SHODAN_API_KEY not set — network intelligence disabled")
if not config.database.neo4j_password:
warnings.append("NEO4J_PASSWORD not set — graph database not configured")
if config.api.jwt_secret_key == "change-this-in-production":
warnings.append("JWT_SECRET_KEY using default — CHANGE THIS IN PRODUCTION")
if not config.github.token:
warnings.append("GITHUB_TOKEN not set — code search will be limited")
return warnings
def print_config_status():
"""Print configuration status for debugging."""
config = get_config()
warnings = validate_config(config)
print("\n" + "=" * 60)
print("ShadowHunter Configuration Status")
print("=" * 60)
print(f"\n📝 Logging: {config.log.level.upper()}")
print(f" Directory: {config.log.dir}")
print(f"\n🗄️ Database:")
print(f" Neo4j: {config.database.neo4j_uri}")
print(f" Redis: {config.database.redis_url}")
print(f"\n🔍 APIs Configured:")
print(f" VirusTotal: {'✓' if config.threat_intel.virustotal_api_key else '✗'}")
print(f" Shodan: {'✓' if config.threat_intel.shodan_api_key else '✗'}")
print(f" HIBP: {'✓' if config.threat_intel.hibp_api_key else '✗'}")
print(f" AbuseIPDB: {'✓' if config.threat_intel.abuseipdb_api_key else '✗'}")
print(f" Bubblemaps: {'✓' if config.blockchain.bubblemaps_api_key else '✗'}")
print(f" GitHub: {'✓' if config.github.token else '✗'}")
print(f"\n🌐 Tor Proxy: {config.tor.proxy_host}:{config.tor.proxy_port}")
if warnings:
print(f"\n⚠️ Warnings ({len(warnings)}):")
for w in warnings:
print(f" • {w}")
else:
print("\n✅ All critical configuration present!")
print("\n" + "=" * 60)
# ============================================================================
# CLI ENTRY POINT
# ============================================================================
if __name__ == "__main__":
print_config_status()