from abc import ABC, abstractmethod from core.Constants import Constants from core.models.orm_models.Location import Location from core.models.Subscription import Subscription from core.models.enum_models import ProtocolChoice from dataclasses import dataclass, field from dataclasses_json import config, Exclude, dataclass_json from pathlib import Path from typing import Optional import os import re import shutil import tempfile from enum import Enum class ProfileType(str, Enum): SESSION = "session" SYSTEM = "system" SYSTEMWIDE_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS] SESSION_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.TOR, ProtocolChoice.SOCK5_PROXY] PROTOCOL_CHOICES = { ProfileType.SYSTEM: SYSTEMWIDE_CHOICES, ProfileType.SESSION: SESSION_CHOICES } CONFIG_NAME = { ProtocolChoice.WIREGUARD: "wg.conf", ProtocolChoice.TOR: "proxy.json", ProtocolChoice.SOCK5_PROXY: "proxy.json", ProtocolChoice.HYSTERIA2: "proxy.json", ProtocolChoice.VLESS: "proxy.json" } SYSTEM_WIDE_BACKUP_CONFIG_NAME = { ProtocolChoice.WIREGUARD: "wg.conf.bak", ProtocolChoice.HYSTERIA2: "proxy.json.bak", ProtocolChoice.VLESS: "proxy.json.bak" } @dataclass_json @dataclass class BaseProfile(ABC): id: int = field( metadata=config(exclude=Exclude.ALWAYS) ) name: str subscription: Optional[Subscription] type: ProfileType # location: Optional[Location] = field(encoder=lambda u: u.id) location: Optional[Location] = field(metadata=config(exclude=Exclude.ALWAYS)) # SQLAlchemy object protocol: ProtocolChoice @abstractmethod def get_wireguard_configuration_path(self): pass @abstractmethod def has_wireguard_configuration(self): pass def get_config_path(self): return BaseProfile.__get_config_path(self.id) def get_data_path(self): return BaseProfile.__get_data_path(self.id) def has_subscription(self): return self.subscription is not None def has_location(self): return self.location is not None def is_session_profile(self): return type(self).__name__ == 'SessionProfile' def is_system_profile(self): return type(self).__name__ == 'SystemProfile' def get_wireguard_configuration_metadata(self, key): configuration = self.get_wireguard_configuration() if configuration is not None: for line in configuration.splitlines(): match = re.match(r'^# {} = (.*)$'.format(re.escape(key)), line) if match: return re.sub(r'[^a-zA-Z0-9+=\-_ /]', '', match.group(1).strip()) return None def get_wireguard_public_keys(self): import configparser wireguard_public_keys = set() configuration = self.get_wireguard_configuration() parsed_configuration = configparser.ConfigParser() if configuration is not None: parsed_configuration.read_string(configuration) for section in parsed_configuration.sections(): if parsed_configuration.has_option(section, 'PublicKey'): wireguard_public_keys.add(parsed_configuration.get(section, 'PublicKey')) return tuple(wireguard_public_keys) def get_wireguard_configuration(self): try: with open(self.get_wireguard_configuration_path(), 'r') as file: return file.read() except (FileNotFoundError, PermissionError): return None def address_security_incident(self): if self.has_wireguard_configuration(): wireguard_configuration_path = Path(self.get_wireguard_configuration_path()) incident_data_path = Path(Constants.HV_INCIDENT_DATA_HOME) incident_data_path.mkdir(parents=True, exist_ok=True) incident_path = Path(tempfile.mkdtemp(dir=incident_data_path, prefix='')) incident_wireguard_configuration_path = f'{incident_path}/{wireguard_configuration_path.name}' try: shutil.copy2(wireguard_configuration_path, incident_wireguard_configuration_path) os.chmod(incident_wireguard_configuration_path, 0o644) except (FileNotFoundError, PermissionError): if incident_path.is_dir(): incident_path_contents = incident_path.iterdir() if not any(incident_path_contents): incident_path.rmdir() @staticmethod def __get_config_path(id: int): return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}' @staticmethod def __get_data_path(id: int): return f'{Constants.HV_PROFILE_DATA_HOME}/{str(id)}'