main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import logging
  5. import time
  6. import tempfile
  7. from flask import Flask, jsonify
  8. from config import Config
  9. from typing import List, Tuple
  10. # Configure logging with custom handler
  11. class NtfyLogHandler(logging.Handler):
  12. """Custom logging handler that sends logs to ntfy health backends"""
  13. def __init__(self, config_obj):
  14. super().__init__()
  15. self.config = config_obj
  16. def emit(self, record):
  17. """Send log record to health backends"""
  18. if hasattr(self.config, 'ntfy_backends_health') and self.config.send_all_logs:
  19. try:
  20. log_message = self.format(record)
  21. # Get configured log level or default to WARNING
  22. min_level = getattr(logging, self.config.log_level.upper(), logging.WARNING)
  23. if record.levelno >= min_level:
  24. # Format message with appropriate emoji based on log level
  25. emoji = "🚨" if record.levelno >= logging.ERROR else "⚠️" if record.levelno >= logging.WARNING else "ℹ️"
  26. title = f"Emergency Access {record.levelname}"
  27. message = f"{emoji} {record.name}: {record.getMessage()}"
  28. send_ntfy_notification(
  29. self.config.ntfy_backends_health,
  30. message,
  31. title
  32. )
  33. except Exception:
  34. # Don't fail the application if logging notification fails
  35. pass
  36. # Configure logging
  37. logging.basicConfig(
  38. level=logging.INFO,
  39. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  40. handlers=[
  41. logging.FileHandler('/var/log/emergency-access.log'),
  42. logging.StreamHandler()
  43. ]
  44. )
  45. logger = logging.getLogger(__name__)
  46. app = Flask(__name__)
  47. # Global config instance
  48. config = None
  49. def send_ntfy_notification(backends: List[str], message: str, title: str = None) -> Tuple[bool, List[str]]:
  50. """
  51. Send notification using dschep/ntfy with dedicated config file
  52. Returns: (success, successful_backends)
  53. """
  54. successful_backends = []
  55. for backend in backends:
  56. try:
  57. # Import ntfy here to avoid import issues during startup
  58. import ntfy
  59. # Set the ntfy config file path
  60. old_config = os.environ.get('NTFY_CONFIG')
  61. os.environ['NTFY_CONFIG'] = config.ntfy_config_path
  62. try:
  63. # Send notification using the backend name from our config file
  64. if title:
  65. ntfy.notify(message, title=title, backend=backend)
  66. else:
  67. ntfy.notify(message, backend=backend)
  68. successful_backends.append(backend)
  69. logger.info(f"Notification sent successfully via {backend}")
  70. finally:
  71. # Restore original config
  72. if old_config:
  73. os.environ['NTFY_CONFIG'] = old_config
  74. elif 'NTFY_CONFIG' in os.environ:
  75. del os.environ['NTFY_CONFIG']
  76. except ImportError:
  77. logger.error(f"ntfy package not available for backend {backend}")
  78. except Exception as e:
  79. logger.error(f"Failed to send notification to {backend}: {str(e)}")
  80. success = len(successful_backends) > 0
  81. return success, successful_backends
  82. def read_file_safely(file_path: str) -> Tuple[bool, str]:
  83. """
  84. Safely read file content
  85. Returns: (success, content)
  86. """
  87. try:
  88. if not os.path.exists(file_path):
  89. logger.error(f"File not found: {file_path}")
  90. return False, f"File not found: {file_path}"
  91. with open(file_path, 'r') as f:
  92. content = f.read().strip()
  93. if not content:
  94. logger.error(f"File is empty: {file_path}")
  95. return False, f"File is empty: {file_path}"
  96. return True, content
  97. except PermissionError:
  98. logger.error(f"Permission denied reading file: {file_path}")
  99. return False, f"Permission denied: {file_path}"
  100. except Exception as e:
  101. logger.error(f"Failed to read file {file_path}: {str(e)}")
  102. return False, f"Failed to read file: {str(e)}"
  103. def get_key_part():
  104. """Emergency key access endpoint"""
  105. logger.warning("EMERGENCY: Key access attempt detected")
  106. try:
  107. # Send notification first - fail-safe approach
  108. notification_success, successful_backends = send_ntfy_notification(
  109. config.ntfy_backends_key,
  110. config.ntfy_key_message,
  111. "EMERGENCY ACCESS ALERT"
  112. )
  113. if not notification_success:
  114. logger.error("CRITICAL: Failed to send notifications to any backend")
  115. return jsonify({
  116. 'error': 'Notification system failure',
  117. 'message': 'Access denied for security reasons'
  118. }), 500
  119. logger.info(f"Notifications sent successfully to: {successful_backends}")
  120. # Read key file
  121. file_success, content = read_file_safely(config.key_file_path)
  122. if not file_success:
  123. logger.error(f"CRITICAL: Failed to read key file: {content}")
  124. return jsonify({
  125. 'error': 'File access failure',
  126. 'message': 'Unable to retrieve key part'
  127. }), 500
  128. logger.warning("EMERGENCY: Key part successfully retrieved and sent")
  129. return jsonify({
  130. 'success': True,
  131. 'key_part': content,
  132. 'timestamp': time.time(),
  133. 'notified_backends': successful_backends
  134. })
  135. except Exception as e:
  136. logger.error(f"CRITICAL: Unexpected error in key access: {str(e)}")
  137. return jsonify({
  138. 'error': 'System error',
  139. 'message': 'Internal server error'
  140. }), 500
  141. def health_check():
  142. """Health check endpoint with dummy file access"""
  143. logger.info("Health check requested")
  144. try:
  145. # Send notification
  146. notification_success, successful_backends = send_ntfy_notification(
  147. config.ntfy_backends_health,
  148. config.ntfy_health_message,
  149. "Health Check"
  150. )
  151. if not notification_success:
  152. logger.error("Health check notification failed")
  153. return jsonify({
  154. 'status': 'error',
  155. 'message': 'Notification system failure'
  156. }), 500
  157. # Read dummy file
  158. file_success, content = read_file_safely(config.dummy_file_path)
  159. if not file_success:
  160. logger.error(f"Health check file read failed: {content}")
  161. return jsonify({
  162. 'status': 'error',
  163. 'message': 'File system failure'
  164. }), 500
  165. logger.info("Health check completed successfully")
  166. return jsonify({
  167. 'status': 'ok',
  168. 'timestamp': time.time(),
  169. 'notified_backends': successful_backends,
  170. 'dummy_content_length': len(content)
  171. })
  172. except Exception as e:
  173. logger.error(f"Health check error: {str(e)}")
  174. return jsonify({
  175. 'status': 'error',
  176. 'message': 'System error'
  177. }), 500
  178. @app.errorhandler(404)
  179. def not_found(error):
  180. """Handle 404 errors silently for security"""
  181. logger.warning(f"404 attempt: {error}")
  182. return jsonify({'error': 'Not found'}), 404
  183. @app.errorhandler(500)
  184. def internal_error(error):
  185. """Handle internal server errors"""
  186. logger.error(f"Internal server error: {error}")
  187. return jsonify({'error': 'Internal server error'}), 500
  188. def validate_setup():
  189. """Validate system setup before starting"""
  190. logger.info("Validating system setup...")
  191. # Check config files exist
  192. if not os.path.exists(config.key_file_path):
  193. logger.error(f"Key file not found: {config.key_file_path}")
  194. return False
  195. if not os.path.exists(config.dummy_file_path):
  196. logger.error(f"Dummy file not found: {config.dummy_file_path}")
  197. return False
  198. # Test file permissions
  199. try:
  200. with open(config.key_file_path, 'r') as f:
  201. f.read(1)
  202. with open(config.dummy_file_path, 'r') as f:
  203. f.read(1)
  204. except Exception as e:
  205. logger.error(f"File permission test failed: {str(e)}")
  206. return False
  207. # Test notification system
  208. logger.info("Testing notification system...")
  209. try:
  210. key_success, _ = send_ntfy_notification(
  211. config.ntfy_backends_key[:1], # Test only first backend
  212. "System startup test - key notifications",
  213. "Emergency Access Startup Test"
  214. )
  215. health_success, _ = send_ntfy_notification(
  216. config.ntfy_backends_health[:1], # Test only first backend
  217. "System startup test - health notifications",
  218. "Emergency Access Startup Test"
  219. )
  220. if not key_success:
  221. logger.error("Key notification system test failed")
  222. return False
  223. if not health_success:
  224. logger.error("Health notification system test failed")
  225. return False
  226. except Exception as e:
  227. logger.warning(f"Notification test failed, but continuing: {str(e)}")
  228. logger.info("System validation completed successfully")
  229. return True
  230. if __name__ == '__main__':
  231. try:
  232. # Load configuration
  233. config = Config()
  234. logger.info("Configuration loaded successfully")
  235. # Add ntfy log handler after config is loaded
  236. if config.send_all_logs:
  237. ntfy_handler = NtfyLogHandler(config)
  238. min_level = getattr(logging, config.log_level.upper(), logging.WARNING)
  239. ntfy_handler.setLevel(min_level)
  240. # Add to root logger to catch all application logs
  241. logging.getLogger().addHandler(ntfy_handler)
  242. # Validate system setup
  243. if not validate_setup():
  244. logger.error("System validation failed, exiting")
  245. sys.exit(1)
  246. # Add Flask routes with config values
  247. app.add_url_rule(config.key_route, 'get_key_part', get_key_part, methods=['GET'])
  248. app.add_url_rule(config.health_route, 'health_check', health_check, methods=['GET'])
  249. logger.info(f"Starting emergency access server on {config.server_host}:{config.server_port}")
  250. logger.info(f"Key route: {config.key_route}")
  251. logger.info(f"Health route: {config.health_route}")
  252. # Run the server on local port for Caddy reverse proxy
  253. app.run(
  254. host=config.server_host,
  255. port=config.server_port,
  256. debug=False,
  257. threaded=True
  258. )
  259. except Exception as e:
  260. logger.error(f"Failed to start server: {str(e)}")
  261. sys.exit(1)