main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. # Load the ntfy config file
  60. ntfy_config = ntfy.config.load_config(config.ntfy_config_path)
  61. # Send notification using the backend name from our config file
  62. if title:
  63. ntfy.notify(message, title=title, backend=backend, config=ntfy_config)
  64. else:
  65. ntfy.notify(message, backend=backend, config=ntfy_config)
  66. successful_backends.append(backend)
  67. logger.info(f"Notification sent successfully via {backend}")
  68. except ImportError:
  69. logger.error(f"ntfy package not available for backend {backend}")
  70. except Exception as e:
  71. logger.error(f"Failed to send notification to {backend}: {str(e)}")
  72. success = len(successful_backends) > 0
  73. return success, successful_backends
  74. def read_file_safely(file_path: str) -> Tuple[bool, str]:
  75. """
  76. Safely read file content
  77. Returns: (success, content)
  78. """
  79. try:
  80. if not os.path.exists(file_path):
  81. logger.error(f"File not found: {file_path}")
  82. return False, f"File not found: {file_path}"
  83. with open(file_path, 'r') as f:
  84. content = f.read().strip()
  85. if not content:
  86. logger.error(f"File is empty: {file_path}")
  87. return False, f"File is empty: {file_path}"
  88. return True, content
  89. except PermissionError:
  90. logger.error(f"Permission denied reading file: {file_path}")
  91. return False, f"Permission denied: {file_path}"
  92. except Exception as e:
  93. logger.error(f"Failed to read file {file_path}: {str(e)}")
  94. return False, f"Failed to read file: {str(e)}"
  95. def get_key_part():
  96. """Emergency key access endpoint"""
  97. logger.warning("EMERGENCY: Key access attempt detected")
  98. try:
  99. # Send notification first - fail-safe approach
  100. notification_success, successful_backends = send_ntfy_notification(
  101. config.ntfy_backends_key,
  102. config.ntfy_key_message,
  103. "EMERGENCY ACCESS ALERT"
  104. )
  105. if not notification_success:
  106. logger.error("CRITICAL: Failed to send notifications to any backend")
  107. return jsonify({
  108. 'error': 'Notification system failure',
  109. 'message': 'Access denied for security reasons'
  110. }), 500
  111. logger.info(f"Notifications sent successfully to: {successful_backends}")
  112. # Read key file
  113. file_success, content = read_file_safely(config.key_file_path)
  114. if not file_success:
  115. logger.error(f"CRITICAL: Failed to read key file: {content}")
  116. return jsonify({
  117. 'error': 'File access failure',
  118. 'message': 'Unable to retrieve key part'
  119. }), 500
  120. logger.warning("EMERGENCY: Key part successfully retrieved and sent")
  121. return jsonify({
  122. 'success': True,
  123. 'key_part': content,
  124. 'timestamp': time.time(),
  125. 'notified_backends': successful_backends
  126. })
  127. except Exception as e:
  128. logger.error(f"CRITICAL: Unexpected error in key access: {str(e)}")
  129. return jsonify({
  130. 'error': 'System error',
  131. 'message': 'Internal server error'
  132. }), 500
  133. def health_check():
  134. """Health check endpoint with dummy file access"""
  135. logger.info("Health check requested")
  136. try:
  137. # Send notification
  138. notification_success, successful_backends = send_ntfy_notification(
  139. config.ntfy_backends_health,
  140. config.ntfy_health_message,
  141. "Health Check"
  142. )
  143. if not notification_success:
  144. logger.error("Health check notification failed")
  145. return jsonify({
  146. 'status': 'error',
  147. 'message': 'Notification system failure'
  148. }), 500
  149. # Read dummy file
  150. file_success, content = read_file_safely(config.dummy_file_path)
  151. if not file_success:
  152. logger.error(f"Health check file read failed: {content}")
  153. return jsonify({
  154. 'status': 'error',
  155. 'message': 'File system failure'
  156. }), 500
  157. logger.info("Health check completed successfully")
  158. return jsonify({
  159. 'status': 'ok',
  160. 'timestamp': time.time(),
  161. 'notified_backends': successful_backends,
  162. 'dummy_content_length': len(content)
  163. })
  164. except Exception as e:
  165. logger.error(f"Health check error: {str(e)}")
  166. return jsonify({
  167. 'status': 'error',
  168. 'message': 'System error'
  169. }), 500
  170. @app.errorhandler(404)
  171. def not_found(error):
  172. """Handle 404 errors silently for security"""
  173. logger.warning(f"404 attempt: {error}")
  174. return jsonify({'error': 'Not found'}), 404
  175. @app.errorhandler(500)
  176. def internal_error(error):
  177. """Handle internal server errors"""
  178. logger.error(f"Internal server error: {error}")
  179. return jsonify({'error': 'Internal server error'}), 500
  180. def validate_setup():
  181. """Validate system setup before starting"""
  182. logger.info("Validating system setup...")
  183. # Check config files exist
  184. if not os.path.exists(config.key_file_path):
  185. logger.error(f"Key file not found: {config.key_file_path}")
  186. return False
  187. if not os.path.exists(config.dummy_file_path):
  188. logger.error(f"Dummy file not found: {config.dummy_file_path}")
  189. return False
  190. # Test file permissions
  191. try:
  192. with open(config.key_file_path, 'r') as f:
  193. f.read(1)
  194. with open(config.dummy_file_path, 'r') as f:
  195. f.read(1)
  196. except Exception as e:
  197. logger.error(f"File permission test failed: {str(e)}")
  198. return False
  199. # Test notification system
  200. logger.info("Testing notification system...")
  201. try:
  202. key_success, _ = send_ntfy_notification(
  203. config.ntfy_backends_key[:1], # Test only first backend
  204. "System startup test - key notifications",
  205. "Emergency Access Startup Test"
  206. )
  207. health_success, _ = send_ntfy_notification(
  208. config.ntfy_backends_health[:1], # Test only first backend
  209. "System startup test - health notifications",
  210. "Emergency Access Startup Test"
  211. )
  212. if not key_success:
  213. logger.error("Key notification system test failed")
  214. return False
  215. if not health_success:
  216. logger.error("Health notification system test failed")
  217. return False
  218. except Exception as e:
  219. logger.warning(f"Notification test failed, but continuing: {str(e)}")
  220. logger.info("System validation completed successfully")
  221. return True
  222. if __name__ == '__main__':
  223. try:
  224. # Load configuration
  225. config = Config()
  226. logger.info("Configuration loaded successfully")
  227. # Add ntfy log handler after config is loaded
  228. if config.send_all_logs:
  229. ntfy_handler = NtfyLogHandler(config)
  230. min_level = getattr(logging, config.log_level.upper(), logging.WARNING)
  231. ntfy_handler.setLevel(min_level)
  232. # Add to root logger to catch all application logs
  233. logging.getLogger().addHandler(ntfy_handler)
  234. # Validate system setup
  235. if not validate_setup():
  236. logger.error("System validation failed, exiting")
  237. sys.exit(1)
  238. # Add Flask routes with config values
  239. app.add_url_rule(config.key_route, 'get_key_part', get_key_part, methods=['GET'])
  240. app.add_url_rule(config.health_route, 'health_check', health_check, methods=['GET'])
  241. logger.info(f"Starting emergency access server on {config.server_host}:{config.server_port}")
  242. logger.info(f"Key route: {config.key_route}")
  243. logger.info(f"Health route: {config.health_route}")
  244. # Run the server on local port for Caddy reverse proxy
  245. app.run(
  246. host=config.server_host,
  247. port=config.server_port,
  248. debug=False,
  249. threaded=True
  250. )
  251. except Exception as e:
  252. logger.error(f"Failed to start server: {str(e)}")
  253. sys.exit(1)