main.py 23 KB

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