main.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import logging
  5. import time
  6. import tempfile
  7. import threading
  8. import subprocess
  9. from flask import Flask, jsonify, request
  10. from werkzeug.security import check_password_hash
  11. from werkzeug.serving import WSGIRequestHandler
  12. from functools import wraps
  13. from config import Config
  14. from typing import List, Tuple
  15. import base64
  16. import signal
  17. # Configure logging with custom handler
  18. class NtfyLogHandler(logging.Handler):
  19. """Custom logging handler that sends logs to ntfy health backends"""
  20. def __init__(self, config_obj):
  21. super().__init__()
  22. self.config = config_obj
  23. def emit(self, record):
  24. """Send log record to health backends"""
  25. if hasattr(self.config, 'ntfy_backends_health') and self.config.send_all_logs:
  26. try:
  27. log_message = self.format(record)
  28. # Get configured log level or default to WARNING
  29. min_level = getattr(logging, self.config.log_level.upper(), logging.WARNING)
  30. if record.levelno >= min_level:
  31. # Format message with appropriate emoji based on log level
  32. emoji = "🚨" if record.levelno >= logging.ERROR else "⚠️" if record.levelno >= logging.WARNING else "ℹ️"
  33. title = f"Emergency Access {record.levelname}"
  34. message = f"{emoji} {record.name}: {record.getMessage()}"
  35. send_ntfy_notification(
  36. self.config.ntfy_backends_health,
  37. message,
  38. title
  39. )
  40. except Exception:
  41. # Don't fail the application if logging notification fails
  42. pass
  43. # Configure logging
  44. logging.basicConfig(
  45. level=logging.INFO,
  46. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  47. handlers=[
  48. logging.FileHandler('/var/log/emergency-access.log'),
  49. logging.StreamHandler()
  50. ]
  51. )
  52. logger = logging.getLogger(__name__)
  53. app = Flask(__name__)
  54. # Global config instance - initialized during main execution
  55. config = None
  56. # Systemd watchdog support
  57. def setup_systemd_watchdog():
  58. """Setup systemd watchdog notifications"""
  59. import os
  60. # Check if we have systemd watchdog enabled
  61. watchdog_usec = os.environ.get('WATCHDOG_USEC')
  62. if not watchdog_usec:
  63. logger.info("Systemd watchdog not enabled")
  64. return False
  65. try:
  66. # Convert microseconds to seconds and send notifications at half the interval
  67. interval = int(watchdog_usec) / 2000000 # Half interval in seconds
  68. logger.info(f"Systemd watchdog enabled, sending notifications every {interval:.1f}s")
  69. def watchdog_ping():
  70. while True:
  71. try:
  72. subprocess.run(['systemd-notify', 'WATCHDOG=1'],
  73. check=False, stdout=subprocess.DEVNULL,
  74. stderr=subprocess.DEVNULL, timeout=5)
  75. time.sleep(interval)
  76. except Exception as e:
  77. logger.warning(f"Failed to send watchdog notification: {e}")
  78. time.sleep(interval)
  79. # Start watchdog thread
  80. watchdog_thread = threading.Thread(target=watchdog_ping, daemon=True)
  81. watchdog_thread.start()
  82. return True
  83. except Exception as e:
  84. logger.warning(f"Failed to setup systemd watchdog: {e}")
  85. return False
  86. def require_auth(key_config=None, is_health=False):
  87. """Decorator for HTTP Basic Authentication"""
  88. def decorator(f):
  89. @wraps(f)
  90. def decorated_function(*args, **kwargs):
  91. if config is None:
  92. logger.error("Configuration not loaded")
  93. return jsonify({'error': 'Server configuration error'}), 500
  94. auth = request.authorization
  95. if not auth:
  96. return jsonify({'error': 'Authentication required'}), 401, {
  97. 'WWW-Authenticate': 'Basic realm="Emergency Access"'
  98. }
  99. # Determine expected credentials
  100. if is_health:
  101. expected_username = config.health_username
  102. expected_password_hash = config.health_password_hash
  103. auth_type = "health check"
  104. else:
  105. if key_config is None:
  106. logger.error("Key configuration not provided for authentication")
  107. return jsonify({'error': 'Server configuration error'}), 500
  108. expected_username = key_config.username
  109. expected_password_hash = key_config.password_hash
  110. auth_type = f"key '{key_config.key_id}'"
  111. # Verify credentials
  112. if (auth.username != expected_username or
  113. not Config.verify_password(auth.password, expected_password_hash)):
  114. logger.warning(f"Authentication failed for {auth_type}: invalid credentials from {request.remote_addr}")
  115. return jsonify({'error': 'Invalid credentials'}), 401, {
  116. 'WWW-Authenticate': 'Basic realm="Emergency Access"'
  117. }
  118. logger.info(f"Authentication successful for {auth_type}")
  119. return f(*args, **kwargs)
  120. return decorated_function
  121. return decorator
  122. def send_ntfy_notification(backends: List[str], message: str, title: str = None) -> Tuple[bool, List[str]]:
  123. """
  124. Send notification using dschep/ntfy with dedicated config file
  125. Returns: (success, successful_backends)
  126. """
  127. successful_backends = []
  128. max_retries = 3
  129. retry_delay = 1
  130. for backend in backends:
  131. success = False
  132. last_error = None
  133. for attempt in range(max_retries):
  134. try:
  135. # Import ntfy here to avoid import issues during startup
  136. try:
  137. import ntfy
  138. from ntfy.config import load_config
  139. except ImportError:
  140. raise Exception("ntfy package not available. Please install with: pip install ntfy")
  141. if config is None:
  142. raise Exception("Configuration not loaded")
  143. # Load the ntfy config file
  144. ntfy_config = load_config(config.ntfy_config_path)
  145. ntfy_config["backends"] = [backend]
  146. # Add timeout to prevent hanging using threading
  147. result = [None]
  148. exception = [None]
  149. def notify_with_timeout():
  150. try:
  151. # Send notification using the backend name from our config file
  152. if title:
  153. result[0] = ntfy.notify(message, title=title, config=ntfy_config)
  154. else:
  155. result[0] = ntfy.notify(message, config=ntfy_config, title="Note")
  156. except Exception as e:
  157. exception[0] = e
  158. thread = threading.Thread(target=notify_with_timeout)
  159. thread.daemon = True
  160. thread.start()
  161. thread.join(timeout=15) # 15 second timeout
  162. if thread.is_alive():
  163. raise Exception("Notification timeout")
  164. if exception[0]:
  165. raise exception[0]
  166. ret = result[0]
  167. if ret == 0:
  168. successful_backends.append(backend)
  169. logger.info(f"Notification sent successfully via {backend}")
  170. success = True
  171. break
  172. else:
  173. raise Exception(f"ntfy returned error code {ret}")
  174. except ImportError as e:
  175. logger.error(f"ntfy package not available for backend {backend}: {e}")
  176. last_error = e
  177. break # Don't retry import errors
  178. except Exception as e:
  179. last_error = e
  180. if attempt < max_retries - 1:
  181. logger.warning(f"Notification attempt {attempt + 1} failed for {backend}: {str(e)}, retrying...")
  182. time.sleep(retry_delay * (attempt + 1)) # Exponential backoff
  183. else:
  184. logger.error(f"All notification attempts failed for {backend}: {str(e)}")
  185. if not success and last_error:
  186. # Don't raise exception - just log failure and continue with other backends
  187. logger.error(f"Failed to send notification to {backend} after {max_retries} attempts: {str(last_error)}")
  188. success = len(successful_backends) > 0
  189. return success, successful_backends
  190. def read_file_safely(file_path: str) -> Tuple[bool, str]:
  191. """
  192. Safely read file content
  193. Returns: (success, content)
  194. """
  195. try:
  196. if not os.path.exists(file_path):
  197. logger.error(f"File not found: {file_path}")
  198. return False, f"File not found: {file_path}"
  199. with open(file_path, 'r') as f:
  200. content = f.read().strip()
  201. if not content:
  202. logger.error(f"File is empty: {file_path}")
  203. return False, f"File is empty: {file_path}"
  204. return True, content
  205. except PermissionError:
  206. logger.error(f"Permission denied reading file: {file_path}")
  207. return False, f"Permission denied: {file_path}"
  208. except Exception as e:
  209. logger.error(f"Failed to read file {file_path}: {str(e)}")
  210. return False, f"Failed to read file: {str(e)}"
  211. def create_key_handler(key_config):
  212. """Create a key access handler for a specific key configuration"""
  213. @require_auth(key_config=key_config)
  214. def get_key_part():
  215. """Emergency key access endpoint"""
  216. if key_config is None:
  217. logger.error("Key configuration is None in get_key_part")
  218. return jsonify({'error': 'Server configuration error'}), 500
  219. logger.warning(f"EMERGENCY: Key access attempt detected for key '{key_config.key_id}'")
  220. try:
  221. # Send notification first - fail-safe approach
  222. notification_success, successful_backends = send_ntfy_notification(
  223. key_config.backends,
  224. key_config.message,
  225. "EMERGENCY ACCESS ALERT"
  226. )
  227. if not notification_success:
  228. logger.error(f"CRITICAL: Failed to send notifications to any backend for key '{key_config.key_id}'")
  229. return jsonify({
  230. 'error': 'Notification system failure',
  231. 'message': 'Access denied for security reasons'
  232. }), 500
  233. logger.info(f"Notifications sent successfully to: {successful_backends} for key '{key_config.key_id}'")
  234. # Read key file
  235. file_success, content = read_file_safely(key_config.file_path)
  236. if not file_success:
  237. logger.error(f"CRITICAL: Failed to read key file for '{key_config.key_id}': {content}")
  238. return jsonify({
  239. 'error': 'File access failure',
  240. 'message': 'Unable to retrieve key part'
  241. }), 500
  242. logger.warning(f"EMERGENCY: Key part successfully retrieved and sent for key '{key_config.key_id}'")
  243. return jsonify({
  244. 'success': True,
  245. 'key_id': key_config.key_id,
  246. 'key_part': content,
  247. 'timestamp': time.time(),
  248. 'notified_backends': successful_backends
  249. })
  250. except Exception as e:
  251. logger.error(f"CRITICAL: Unexpected error in key access for '{key_config.key_id}': {str(e)}")
  252. return jsonify({
  253. 'error': 'System error',
  254. 'message': 'Internal server error'
  255. }), 500
  256. return get_key_part
  257. @require_auth(is_health=True)
  258. def health_check():
  259. """Health check endpoint that verifies both health monitoring and all key request functionality"""
  260. logger.info("Health check requested")
  261. if config is None:
  262. logger.error("Configuration not loaded during health check")
  263. return jsonify({'status': 'error', 'message': 'Configuration not loaded'}), 500
  264. try:
  265. # Test health notification system
  266. health_notification_success, health_backends = send_ntfy_notification(
  267. config.ntfy_backends_health,
  268. config.ntfy_health_message,
  269. "Health Check"
  270. )
  271. # Test dummy file access
  272. dummy_file_success, dummy_content = read_file_safely(config.dummy_file_path)
  273. # Test all key files access (without exposing content)
  274. key_files_status = {}
  275. all_key_files_ok = True
  276. for key_id, key_config in config.keys.items():
  277. key_file_success, key_content = read_file_safely(key_config.file_path)
  278. key_files_status[key_id] = key_file_success
  279. if not key_file_success:
  280. all_key_files_ok = False
  281. # Test all key notification backends
  282. key_backends_status = {}
  283. all_key_backends_ok = True
  284. for key_id, key_config in config.keys.items():
  285. try:
  286. # Test notification without actually sending
  287. backend_test_success = len(key_config.backends) > 0
  288. key_backends_status[key_id] = {
  289. 'backends': key_config.backends,
  290. 'success': backend_test_success
  291. }
  292. if not backend_test_success:
  293. all_key_backends_ok = False
  294. except Exception as e:
  295. key_backends_status[key_id] = {
  296. 'backends': key_config.backends,
  297. 'success': False,
  298. 'error': str(e)
  299. }
  300. all_key_backends_ok = False
  301. # Determine overall health status
  302. all_systems_ok = (health_notification_success and
  303. dummy_file_success and
  304. all_key_files_ok and
  305. all_key_backends_ok)
  306. if not all_systems_ok:
  307. error_details = []
  308. if not health_notification_success:
  309. error_details.append("health notifications failed")
  310. if not dummy_file_success:
  311. error_details.append(f"dummy file access failed: {dummy_content}")
  312. # Add key-specific errors
  313. for key_id, status in key_files_status.items():
  314. if not status:
  315. error_details.append(f"key file access failed for '{key_id}'")
  316. for key_id, status in key_backends_status.items():
  317. if not status['success']:
  318. error_msg = f"key backends failed for '{key_id}'"
  319. if 'error' in status:
  320. error_msg += f": {status['error']}"
  321. error_details.append(error_msg)
  322. logger.error(f"Health check failed: {', '.join(error_details)}")
  323. return jsonify({
  324. 'status': 'error',
  325. 'message': 'System components failed',
  326. 'details': error_details,
  327. 'health_notifications': health_notification_success,
  328. 'dummy_file_access': dummy_file_success,
  329. 'key_files_status': key_files_status,
  330. 'key_backends_status': key_backends_status
  331. }), 500
  332. logger.info("Health check completed successfully - all systems operational")
  333. return jsonify({
  334. 'status': 'ok',
  335. 'timestamp': time.time(),
  336. 'health_backends_notified': health_backends,
  337. 'dummy_content_length': len(dummy_content),
  338. 'keys_accessible': len(key_files_status),
  339. 'key_files_status': key_files_status,
  340. 'key_backends_status': key_backends_status,
  341. 'emergency_system_ready': True
  342. })
  343. except Exception as e:
  344. logger.error(f"Health check error: {str(e)}")
  345. return jsonify({
  346. 'status': 'error',
  347. 'message': 'System error',
  348. 'error': str(e)
  349. }), 500
  350. @app.errorhandler(404)
  351. def not_found(error):
  352. """Handle 404 errors silently for security"""
  353. logger.warning(f"404 attempt: {error}")
  354. return jsonify({'error': 'Not found'}), 404
  355. @app.errorhandler(500)
  356. def internal_error(error):
  357. """Handle internal server errors"""
  358. logger.error(f"Internal server error: {error}")
  359. return jsonify({'error': 'Internal server error'}), 500
  360. def validate_setup():
  361. """Validate system setup before starting"""
  362. logger.info("Validating system setup...")
  363. if config is None:
  364. logger.error("Configuration not loaded")
  365. return False
  366. # Check dummy file exists
  367. if not os.path.exists(config.dummy_file_path):
  368. logger.error(f"Dummy file not found: {config.dummy_file_path}")
  369. return False
  370. # Test dummy file permissions
  371. try:
  372. with open(config.dummy_file_path, 'r') as f:
  373. f.read(1)
  374. except Exception as e:
  375. logger.error(f"Dummy file permission test failed: {str(e)}")
  376. return False
  377. # Validate all key configurations
  378. for key_id, key_config in config.keys.items():
  379. logger.info(f"Validating key '{key_id}'...")
  380. # Check key file exists
  381. if not os.path.exists(key_config.file_path):
  382. logger.error(f"Key file not found for '{key_id}': {key_config.file_path}")
  383. return False
  384. # Test key file permissions
  385. try:
  386. with open(key_config.file_path, 'r') as f:
  387. f.read(1)
  388. except Exception as e:
  389. logger.error(f"Key file permission test failed for '{key_id}': {str(e)}")
  390. return False
  391. # Validate backends are configured
  392. if not key_config.backends:
  393. logger.error(f"No notification backends configured for key '{key_id}'")
  394. return False
  395. # Test notification system
  396. logger.info("Testing notification system...")
  397. try:
  398. # Test health notification system
  399. health_success, _ = send_ntfy_notification(
  400. config.ntfy_backends_health[:1], # Test only first backend
  401. "System startup test - health notifications",
  402. "Emergency Access Startup Test"
  403. )
  404. if not health_success:
  405. logger.error("Health notification system test failed")
  406. return False
  407. # Test each key's notification backends
  408. for key_id, key_config in config.keys.items():
  409. key_success, _ = send_ntfy_notification(
  410. key_config.backends[:1], # Test only first backend
  411. f"System startup test - key '{key_id}' notifications",
  412. "Emergency Access Startup Test"
  413. )
  414. if not key_success:
  415. logger.error(f"Key notification system test failed for '{key_id}'")
  416. return False
  417. except Exception as e:
  418. logger.warning(f"Notification test failed, but continuing: {str(e)}")
  419. logger.info("System validation completed successfully")
  420. return True
  421. class ProductionRequestHandler(WSGIRequestHandler):
  422. """Custom request handler with improved error handling"""
  423. def log_error(self, format, *args):
  424. """Override to use our logger"""
  425. logger.error(f"HTTP Error: {format % args}")
  426. def log_message(self, format, *args):
  427. """Override to use our logger"""
  428. logger.info(f"HTTP: {format % args}")
  429. def main():
  430. global config
  431. try:
  432. # Load configuration
  433. config = Config()
  434. logger.info("Configuration loaded successfully")
  435. # Add ntfy log handler after config is loaded
  436. if config.send_all_logs:
  437. ntfy_handler = NtfyLogHandler(config)
  438. min_level = getattr(logging, config.log_level.upper(), logging.WARNING)
  439. ntfy_handler.setLevel(min_level)
  440. # Add to root logger to catch all application logs
  441. logging.getLogger().addHandler(ntfy_handler)
  442. # Validate system setup
  443. if not validate_setup():
  444. logger.error("System validation failed, exiting")
  445. sys.exit(1)
  446. # Add Flask routes dynamically for each key
  447. for key_id, key_config in config.keys.items():
  448. handler = create_key_handler(key_config)
  449. endpoint_name = f'get_key_part_{key_id}'
  450. app.add_url_rule(key_config.route, endpoint_name, handler, methods=['GET'])
  451. logger.info(f"Registered authenticated key route for '{key_id}': {key_config.route}")
  452. # Add health check route
  453. app.add_url_rule(config.health_route, 'health_check', health_check, methods=['GET'])
  454. # Setup systemd watchdog
  455. watchdog_enabled = setup_systemd_watchdog()
  456. logger.info(f"Starting emergency access server on {config.server_host}:{config.server_port}")
  457. logger.info(f"Health route: {config.health_route}")
  458. logger.info(f"Configured {len(config.keys)} key(s)")
  459. logger.info(f"Systemd watchdog: {'enabled' if watchdog_enabled else 'disabled'}")
  460. # Notify systemd that we're ready
  461. try:
  462. subprocess.run(['systemd-notify', 'READY=1'],
  463. check=False, stdout=subprocess.DEVNULL,
  464. stderr=subprocess.DEVNULL, timeout=5)
  465. logger.info("Sent READY=1 to systemd")
  466. except Exception as e:
  467. logger.warning(f"Failed to notify systemd ready: {e}")
  468. # Use production-ready server with better error handling
  469. try:
  470. from waitress import serve
  471. logger.info("Using Waitress WSGI server for production")
  472. serve(
  473. app,
  474. host=config.server_host,
  475. port=config.server_port,
  476. threads=6,
  477. connection_limit=100,
  478. cleanup_interval=30,
  479. channel_timeout=120
  480. )
  481. except ImportError:
  482. logger.warning("Waitress not available, falling back to Flask dev server")
  483. app.run(
  484. host=config.server_host,
  485. port=config.server_port,
  486. debug=False,
  487. threaded=True,
  488. request_handler=ProductionRequestHandler
  489. )
  490. except KeyboardInterrupt:
  491. logger.info("Received keyboard interrupt, shutting down gracefully")
  492. except Exception as e:
  493. logger.error(f"Failed to start server: {str(e)}")
  494. if config and hasattr(config, 'ntfy_backends_health'):
  495. try:
  496. send_ntfy_notification(
  497. config.ntfy_backends_health,
  498. f"🚨 Emergency Access server failed to start: {str(e)}",
  499. "Emergency Access CRITICAL"
  500. )
  501. except Exception:
  502. pass
  503. sys.exit(1)
  504. finally:
  505. logger.info("Emergency Access server shutdown complete")
  506. if __name__ == '__main__':
  507. main()