Compare commits
No commits in common. "cb11e11e49faa13c02fa4b4cb89ad8ca46c4e50b" and "3afd4a8f9b2c463d9866e330b77c37abefcfea27" have entirely different histories.
cb11e11e49
...
3afd4a8f9b
3 changed files with 398 additions and 110 deletions
|
|
@ -26,13 +26,15 @@ from subprocess import CalledProcessError
|
||||||
from typing import Union, Optional, Any
|
from typing import Union, Optional, Any
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
# import re
|
||||||
|
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
|
# import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
# import sys
|
|
||||||
# import re
|
|
||||||
|
|
||||||
|
|
||||||
class ConnectionController:
|
class ConnectionController:
|
||||||
|
|
@ -58,6 +60,87 @@ class ConnectionController:
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def establish_connection(profile: Union[SessionProfile, SystemProfile], ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
||||||
|
# connection = profile.connection
|
||||||
|
|
||||||
|
# # needs_proxy_configuration comes from the child connection models
|
||||||
|
# # for the system it returns false blindly. for the session is checks if the connection type is masked.
|
||||||
|
# # if connection.masked and not profile.has_proxy_configuration():
|
||||||
|
# if connection.needs_proxy_configuration() and not profile.has_proxy_configuration():
|
||||||
|
|
||||||
|
# if profile.has_subscription():
|
||||||
|
|
||||||
|
# if not profile.subscription.has_been_activated():
|
||||||
|
# ProfileController.activate_subscription(profile, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# proxy_configuration = ConnectionController.with_preferred_connection(profile.subscription.billing_code, task=WebServiceApiService.get_proxy_configuration, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# if proxy_configuration is None:
|
||||||
|
# raise InvalidSubscriptionError()
|
||||||
|
|
||||||
|
# profile.attach_proxy_configuration(proxy_configuration)
|
||||||
|
|
||||||
|
# else:
|
||||||
|
# raise MissingSubscriptionError()
|
||||||
|
|
||||||
|
# # The needs_wireguard_configuration comes from the connection model,
|
||||||
|
# # and can be transitioned to get it directly from the object's data
|
||||||
|
# # The has_wireguard_configuration comes from each polymorph object doing an os check on if the wg config exists
|
||||||
|
# if connection.needs_wireguard_configuration() and not profile.has_wireguard_configuration():
|
||||||
|
|
||||||
|
# if profile.has_subscription():
|
||||||
|
|
||||||
|
# if not profile.subscription.has_been_activated():
|
||||||
|
# ProfileController.activate_subscription(profile, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# ProfileController.register_wireguard_session(profile, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# else:
|
||||||
|
|
||||||
|
# if profile.is_system_profile():
|
||||||
|
|
||||||
|
# if system_uses_wireguard_interface() and SystemStateController.exists():
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# terminate_system_connection()
|
||||||
|
# except ConnectionTerminationError:
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# raise MissingSubscriptionError()
|
||||||
|
|
||||||
|
# if profile.is_session_profile():
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# return ConnectionController.establish_session_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# except ConnectionError:
|
||||||
|
|
||||||
|
# if ConnectionController.__should_renegotiate(profile):
|
||||||
|
|
||||||
|
# ProfileController.register_wireguard_session(profile, connection_observer=connection_observer)
|
||||||
|
# return ConnectionController.establish_session_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# else:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# if profile.is_system_profile():
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# return establish_system_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# except ConnectionError:
|
||||||
|
|
||||||
|
# if ConnectionController.__should_renegotiate(profile):
|
||||||
|
|
||||||
|
# ProfileController.register_wireguard_session(profile, connection_observer=connection_observer)
|
||||||
|
# return establish_system_connection(profile, ignore=ignore, connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# else:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None):
|
def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
@ -110,6 +193,46 @@ class ConnectionController:
|
||||||
|
|
||||||
return proxy_port_number or port_number
|
return proxy_port_number or port_number
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def establish_system_connection(profile: SystemProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
||||||
|
# if ConfigurationController.get_endpoint_verification_enabled():
|
||||||
|
# ProfileController.verify_wireguard_endpoint(profile, ignore=ignore)
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.__establish_system_connection(profile, connection_observer)
|
||||||
|
|
||||||
|
# except ConnectionError:
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.terminate_system_connection()
|
||||||
|
# except ConnectionTerminationError:
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# except CalledProcessError:
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.terminate_system_connection()
|
||||||
|
# except ConnectionTerminationError:
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.__establish_system_connection(profile, connection_observer)
|
||||||
|
|
||||||
|
# except (ConnectionError, CalledProcessError):
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.terminate_system_connection()
|
||||||
|
# except ConnectionTerminationError:
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# ConnectionController.terminate_tor_connection()
|
||||||
|
# time.sleep(1.0)
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def establish_tor_connection(connection_observer: Optional[ConnectionObserver] = None):
|
def establish_tor_connection(connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
@ -203,6 +326,25 @@ class ConnectionController:
|
||||||
|
|
||||||
return subprocess.Popen(('proxychains4', '-f', proxychains_configuration_file_path, 'microsocks', '-p', str(proxy_port_number)), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
return subprocess.Popen(('proxychains4', '-f', proxychains_configuration_file_path, 'microsocks', '-p', str(proxy_port_number)), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def terminate_system_connection():
|
||||||
|
|
||||||
|
# if shutil.which('nmcli') is None:
|
||||||
|
# raise CommandNotFoundError('nmcli')
|
||||||
|
|
||||||
|
# if SystemStateController.exists():
|
||||||
|
|
||||||
|
# process = subprocess.Popen(('nmcli', 'connection', 'delete', 'wg'), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||||
|
# completed_successfully = not bool(os.waitpid(process.pid, 0)[1] >> 8)
|
||||||
|
|
||||||
|
# if completed_successfully or not ConnectionController.system_uses_wireguard_interface():
|
||||||
|
|
||||||
|
# subprocess.run(('nmcli', 'connection', 'delete', 'hv-ipv6-sink'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
# ConnectionController.terminate_tor_connection()
|
||||||
|
# SystemState.dissolve()
|
||||||
|
|
||||||
|
# else:
|
||||||
|
# raise ConnectionTerminationError('The connection could not be terminated.')
|
||||||
|
|
||||||
|
|
||||||
# Stays here for Tor based only. Will move with Tor later.
|
# Stays here for Tor based only. Will move with Tor later.
|
||||||
|
|
@ -214,6 +356,107 @@ class ConnectionController:
|
||||||
https=f'socks5h://127.0.0.1:{port_number}'
|
https=f'socks5h://127.0.0.1:{port_number}'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def await_connection(port_number: Optional[int] = None, connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
||||||
|
# if port_number is None:
|
||||||
|
# ConnectionController.await_network_interface()
|
||||||
|
|
||||||
|
# for retry_count in range(Constants.MAX_CONNECTION_ATTEMPTS):
|
||||||
|
|
||||||
|
# if connection_observer is not None:
|
||||||
|
|
||||||
|
# connection_observer.notify('connecting', dict(
|
||||||
|
# retry_interval=Constants.CONNECTION_RETRY_INTERVAL,
|
||||||
|
# maximum_number_of_attempts=Constants.MAX_CONNECTION_ATTEMPTS,
|
||||||
|
# attempt_count=retry_count + 1
|
||||||
|
# ))
|
||||||
|
|
||||||
|
# try:
|
||||||
|
|
||||||
|
# ConnectionController.__test_connection(port_number)
|
||||||
|
# return
|
||||||
|
|
||||||
|
# except ConnectionError:
|
||||||
|
|
||||||
|
# time.sleep(Constants.CONNECTION_RETRY_INTERVAL)
|
||||||
|
# retry_count += 1
|
||||||
|
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def await_network_interface():
|
||||||
|
|
||||||
|
# network_interface_is_activated = False
|
||||||
|
|
||||||
|
# retry_interval = .5
|
||||||
|
# maximum_number_of_attempts = 10
|
||||||
|
# attempt = 0
|
||||||
|
|
||||||
|
# while not network_interface_is_activated and attempt < maximum_number_of_attempts:
|
||||||
|
|
||||||
|
# time.sleep(retry_interval)
|
||||||
|
|
||||||
|
# network_interface_is_activated = ConnectionController.system_uses_wireguard_interface()
|
||||||
|
# attempt += 1
|
||||||
|
|
||||||
|
# if not network_interface_is_activated:
|
||||||
|
# raise ConnectionError('The network interface could not be activated.')
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def system_uses_wireguard_interface():
|
||||||
|
|
||||||
|
# if shutil.which('ip') is None:
|
||||||
|
# raise CommandNotFoundError('ip')
|
||||||
|
|
||||||
|
# process = subprocess.Popen(('ip', 'route', 'get', '192.0.2.1'), stdout=subprocess.PIPE)
|
||||||
|
# process_output = str(process.stdout.read())
|
||||||
|
|
||||||
|
# return bool(re.search('dev wg', str(process_output)))
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def __establish_system_connection(profile: SystemProfile, connection_observer: Optional[ConnectionObserver] = None):
|
||||||
|
|
||||||
|
# if shutil.which('dbus-send') is None:
|
||||||
|
# raise CommandNotFoundError('dbus-send')
|
||||||
|
|
||||||
|
# if shutil.which('nmcli') is None:
|
||||||
|
# raise CommandNotFoundError('nmcli')
|
||||||
|
|
||||||
|
# ConnectionController.terminate_system_connection()
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# process_output = subprocess.check_output(('nmcli', 'connection', 'import', '--temporary', 'type', 'wireguard', 'file', profile.get_wireguard_configuration_path()), text=True)
|
||||||
|
# except CalledProcessError:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# try:
|
||||||
|
|
||||||
|
# connection_id = (m := re.search(r'(?<=\()([a-f0-9-]+?)(?=\))', process_output)) and m.group(1)
|
||||||
|
# ipv6_method = subprocess.check_output(('nmcli', '-g', 'ipv6.method', 'connection', 'show', connection_id), text=True).strip()
|
||||||
|
|
||||||
|
# except CalledProcessError:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# if ipv6_method in ('disabled', 'ignore'):
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# subprocess.run(('dbus-send', '--system', '--print-reply', '--dest=org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager', 'org.freedesktop.DBus.Properties.Set', 'string:org.freedesktop.NetworkManager', 'string:ConnectivityCheckEnabled', 'variant:boolean:false'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||||
|
# except CalledProcessError:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# subprocess.run(('nmcli', 'connection', 'add', 'type', 'dummy', 'save', 'no', 'con-name', 'hv-ipv6-sink', 'ifname', 'hvipv6sink0', 'ipv6.method', 'manual', 'ipv6.addresses', 'fd7a:fd4b:54e3:077c::/64', 'ipv6.gateway', 'fd7a:fd4b:54e3:077c::1', 'ipv6.dns', '::1', 'ipv6.route-metric', '72'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||||
|
# except CalledProcessError:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# SystemStateController.create(profile.id)
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# ConnectionController.await_connection(connection_observer=connection_observer)
|
||||||
|
|
||||||
|
# except ConnectionError:
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def __with_tor_connection(*args, task: Callable[..., Any], connection_observer: Optional[ConnectionObserver] = None, **kwargs):
|
def __with_tor_connection(*args, task: Callable[..., Any], connection_observer: Optional[ConnectionObserver] = None, **kwargs):
|
||||||
|
|
@ -227,3 +470,56 @@ class ConnectionController:
|
||||||
ConnectionController.terminate_tor_session_connection(port_number)
|
ConnectionController.terminate_tor_session_connection(port_number)
|
||||||
|
|
||||||
return task_output
|
return task_output
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def __test_connection(port_number: Optional[int] = None, timeout: float = 4.0):
|
||||||
|
|
||||||
|
# request_urls = [Constants.PING_URL]
|
||||||
|
# proxies = None
|
||||||
|
|
||||||
|
# if os.environ.get('PING_URL') is None:
|
||||||
|
|
||||||
|
# request_urls.extend([
|
||||||
|
# 'https://hc1.simplifiedprivacy.net',
|
||||||
|
# 'https://hc2.simplifiedprivacy.org',
|
||||||
|
# 'https://hc3.hydraveil.net'
|
||||||
|
# ])
|
||||||
|
|
||||||
|
# random.shuffle(request_urls)
|
||||||
|
|
||||||
|
# if port_number is not None:
|
||||||
|
# proxies = ConnectionController.get_proxies(port_number)
|
||||||
|
|
||||||
|
# for request_url in request_urls:
|
||||||
|
|
||||||
|
# command = [
|
||||||
|
# sys.executable, '-u', '-c', 'import requests, sys\n'
|
||||||
|
# 'try:\n'
|
||||||
|
# f' response = requests.get(\'{request_url}\', proxies={proxies}, timeout={timeout})\n'
|
||||||
|
# ' response.raise_for_status(); print(response.text)\n'
|
||||||
|
# 'except requests.exceptions.RequestException:\n'
|
||||||
|
# ' sys.exit(1)'
|
||||||
|
# ]
|
||||||
|
|
||||||
|
# try:
|
||||||
|
|
||||||
|
# _response = subprocess.check_output(command, text=True, timeout=timeout)
|
||||||
|
# return None
|
||||||
|
|
||||||
|
# except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# raise ConnectionError('The connection could not be established.')
|
||||||
|
|
||||||
|
# @staticmethod
|
||||||
|
# def __should_renegotiate(profile: Union[SessionProfile, SystemProfile]):
|
||||||
|
|
||||||
|
# if not profile.has_subscription():
|
||||||
|
# raise MissingSubscriptionError()
|
||||||
|
|
||||||
|
# if profile.connection.needs_wireguard_configuration() and profile.has_wireguard_configuration():
|
||||||
|
|
||||||
|
# if profile.subscription.has_been_activated():
|
||||||
|
# return True
|
||||||
|
|
||||||
|
# return False
|
||||||
|
|
@ -2,12 +2,11 @@ from core.services.networking.general_connection_tools.testing_evaluating import
|
||||||
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
from core.services.keys_and_verifications.endpoint_verification import verify_wireguard_endpoint
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.services.networking.systemwide.systemwide_utils import extract_wg_interface_name, check_system_prereqs, get_firewall_setting, get_dns_setting
|
from core.services.networking.systemwide.systemwide_utils import extract_wg_interface_name, check_system_prereqs, get_firewall_setting, get_dns_setting
|
||||||
# from core.services.networking.general_connection_tools.config_tools import extract_endpoint_ip, extract_dns
|
from core.services.networking.general_connection_tools.config_tools import extract_endpoint_ip, extract_dns
|
||||||
from core.services.networking.systemwide import killswitch
|
from core.services.networking.systemwide import killswitch, dns
|
||||||
from core.services.networking.systemwide.dns_tools.process_dns_result import orchestrate_dns_check
|
from core.services.networking.systemwide.dns_tools.process_dns_result import orchestrate_dns_check
|
||||||
from core.services.networking.systemwide.dns_tools.SearchResult import SearchResult, SearchError
|
from core.services.networking.systemwide.dns_tools.SearchResult import SearchResult, SearchError
|
||||||
from core.services.networking.systemwide.wireguard.nmcli_tools import setup_nmcli_connection, setup_ipv6_sinkhole
|
from core.services.networking.systemwide.wireguard.nmcli_tools import setup_nmcli_connection, setup_ipv6_sinkhole
|
||||||
from core.services.networking.systemwide.wireguard.wg_firewall_dns import set_dns, revert_dns, turn_on_firewall, check_and_kill_firewall
|
|
||||||
from core.errors.logger import logger
|
from core.errors.logger import logger
|
||||||
|
|
||||||
from core.Constants import Constants
|
from core.Constants import Constants
|
||||||
|
|
@ -28,6 +27,104 @@ import subprocess
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def set_dns(profile_id: str, network_interface: str) -> Result:
|
||||||
|
do_they_even_use_systemd = dns.is_systemd_enabled()
|
||||||
|
|
||||||
|
if not do_they_even_use_systemd.valid:
|
||||||
|
error_msg = "You don't use SystemD, so we are skipping setting your DNS."
|
||||||
|
logger.info(error_msg)
|
||||||
|
return Result(valid=True, message=error_msg) # true to not prompt errors
|
||||||
|
|
||||||
|
dns_should_be = extract_dns(profile_id)
|
||||||
|
|
||||||
|
logger.info(f"[CONNECT] About to set the DNS for {network_interface}..")
|
||||||
|
return dns.set_on(network_interface=network_interface, dns_should_be=dns_should_be)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def revert_dns() -> Result:
|
||||||
|
do_they_even_use_systemd = dns.is_systemd_enabled()
|
||||||
|
|
||||||
|
if not do_they_even_use_systemd.valid:
|
||||||
|
error_msg = "You don't use SystemD, so we are skipping setting your DNS."
|
||||||
|
logger.info(error_msg)
|
||||||
|
return Result(valid=True, message=error_msg) # true to not prompt errors
|
||||||
|
|
||||||
|
logger.info("Reverting DNS Settings..")
|
||||||
|
turn_off = dns.revert()
|
||||||
|
logger.info(f"The result of the turn off is {turn_off.valid}")
|
||||||
|
if not turn_off.valid:
|
||||||
|
logger.error(f"Critical DNS Error! Could NOT turn off DNS. Error type: {turn_off.error_type} with {turn_off.message}")
|
||||||
|
return turn_off.valid
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def turn_on_firewall(profile_id: str, wg_interface_name: str) -> Result:
|
||||||
|
"""
|
||||||
|
Purpose:
|
||||||
|
This is a wireguard specific function, using the WG interface,
|
||||||
|
but the underlying killswitch.arm function it uses is protocol neutral.
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1) Get the WG interface from the process output
|
||||||
|
2) Get the server IP from the backup WG config
|
||||||
|
3) Use the killswitch's arm
|
||||||
|
"""
|
||||||
|
logger.info(f"[SYSTEMWIDE WG] Turning on Firewall..")
|
||||||
|
|
||||||
|
server_ip_address = extract_endpoint_ip(profile_id)
|
||||||
|
if wg_interface_name != 'wg':
|
||||||
|
logger.info(f"Note: The WG interface is NOT WG. It's {wg_interface_name}. Be careful about what we kill switch compared to what goes up. Although we kill the nftable rule regardless on down.")
|
||||||
|
|
||||||
|
return killswitch.arm(
|
||||||
|
server_ip=server_ip_address,
|
||||||
|
tunnel_if=wg_interface_name,
|
||||||
|
internal_subnet=None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# This raises errors on failure.
|
||||||
|
def check_and_kill_firewall():
|
||||||
|
firewall_on = killswitch.status() # produces a boolean
|
||||||
|
logger.info(f"The Firewall is currently: {firewall_on}")
|
||||||
|
|
||||||
|
# is it even armed? if not, get lost,
|
||||||
|
if firewall_on:
|
||||||
|
# if it's armed, kill it,
|
||||||
|
logger.info(f"Killing the firewall..")
|
||||||
|
disable_result_object = killswitch.disarm() # produces a Result Object
|
||||||
|
|
||||||
|
# did that work?
|
||||||
|
if disable_result_object.valid:
|
||||||
|
logger.info(f"Success! We disabled the firewall correctly.")
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
error_msg = f"Firewall can't be disabled: {disable_result_object.message}"
|
||||||
|
logger.error(error_msg)
|
||||||
|
|
||||||
|
# if the systemwide_raiser didn't catch it with the reason, then..
|
||||||
|
raise ConnectionTerminationError(error_msg)
|
||||||
|
else:
|
||||||
|
logger.info("We are skipping disabling the firewall, because it's already off.")
|
||||||
|
|
||||||
|
|
||||||
|
# This is dead code right now
|
||||||
|
def confirm_dns_is_reverted(wg_interface_name: str = 'wg'):
|
||||||
|
do_they_even_use_systemd = dns.is_systemd_enabled()
|
||||||
|
|
||||||
|
if not do_they_even_use_systemd:
|
||||||
|
return True
|
||||||
|
|
||||||
|
check_on_dns = orchestrate_dns_check(wg_interface_name)
|
||||||
|
|
||||||
|
if check_on_dns.valid:
|
||||||
|
logger.error("CRITICAL DNS PROBLEM! We turned WG off, but the DNS check shows it's still on. Trying again..")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
logger.info("We turned WG off, and the DNS check shows it reverted also. This is great.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def terminate_system_connection(
|
def terminate_system_connection(
|
||||||
firewall_setting: Optional[bool] = get_firewall_setting(),
|
firewall_setting: Optional[bool] = get_firewall_setting(),
|
||||||
dns_setting: Optional[bool] = get_dns_setting()
|
dns_setting: Optional[bool] = get_dns_setting()
|
||||||
|
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
from core.models.Result import Result, ResultError
|
|
||||||
from core.services.networking.systemwide import killswitch, dns
|
|
||||||
from core.services.networking.general_connection_tools.config_tools import extract_endpoint_ip, extract_dns
|
|
||||||
from core.errors.logger import logger
|
|
||||||
|
|
||||||
def set_dns(profile_id: str, network_interface: str) -> Result:
|
|
||||||
do_they_even_use_systemd = dns.is_systemd_enabled()
|
|
||||||
|
|
||||||
if not do_they_even_use_systemd.valid:
|
|
||||||
error_msg = "You don't use SystemD, so we are skipping setting your DNS."
|
|
||||||
logger.info(error_msg)
|
|
||||||
return Result(valid=True, message=error_msg) # true to not prompt errors
|
|
||||||
|
|
||||||
dns_should_be = extract_dns(profile_id)
|
|
||||||
|
|
||||||
logger.info(f"[CONNECT] About to set the DNS for {network_interface}..")
|
|
||||||
return dns.set_on(network_interface=network_interface, dns_should_be=dns_should_be)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def revert_dns() -> Result:
|
|
||||||
do_they_even_use_systemd = dns.is_systemd_enabled()
|
|
||||||
|
|
||||||
if not do_they_even_use_systemd.valid:
|
|
||||||
error_msg = "You don't use SystemD, so we are skipping setting your DNS."
|
|
||||||
logger.info(error_msg)
|
|
||||||
return Result(valid=True, message=error_msg) # true to not prompt errors
|
|
||||||
|
|
||||||
logger.info("Reverting DNS Settings..")
|
|
||||||
turn_off = dns.revert()
|
|
||||||
logger.info(f"The result of the turn off is {turn_off.valid}")
|
|
||||||
if not turn_off.valid:
|
|
||||||
logger.error(f"Critical DNS Error! Could NOT turn off DNS. Error type: {turn_off.error_type} with {turn_off.message}")
|
|
||||||
return turn_off.valid
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def turn_on_firewall(profile_id: str, wg_interface_name: str) -> Result:
|
|
||||||
"""
|
|
||||||
Purpose:
|
|
||||||
This is a wireguard specific function, using the WG interface,
|
|
||||||
but the underlying killswitch.arm function it uses is protocol neutral.
|
|
||||||
|
|
||||||
Steps:
|
|
||||||
1) Get the WG interface from the process output
|
|
||||||
2) Get the server IP from the backup WG config
|
|
||||||
3) Use the killswitch's arm
|
|
||||||
"""
|
|
||||||
logger.info(f"[SYSTEMWIDE WG] Turning on Firewall..")
|
|
||||||
|
|
||||||
server_ip_address = extract_endpoint_ip(profile_id)
|
|
||||||
if wg_interface_name != 'wg':
|
|
||||||
logger.info(f"Note: The WG interface is NOT WG. It's {wg_interface_name}. Be careful about what we kill switch compared to what goes up. Although we kill the nftable rule regardless on down.")
|
|
||||||
|
|
||||||
return killswitch.arm(
|
|
||||||
server_ip=server_ip_address,
|
|
||||||
tunnel_if=wg_interface_name,
|
|
||||||
internal_subnet=None
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# This raises errors on failure.
|
|
||||||
def check_and_kill_firewall():
|
|
||||||
firewall_on = killswitch.status() # produces a boolean
|
|
||||||
logger.info(f"The Firewall is currently: {firewall_on}")
|
|
||||||
|
|
||||||
# is it even armed? if not, get lost,
|
|
||||||
if firewall_on:
|
|
||||||
# if it's armed, kill it,
|
|
||||||
logger.info(f"Killing the firewall..")
|
|
||||||
disable_result_object = killswitch.disarm() # produces a Result Object
|
|
||||||
|
|
||||||
# did that work?
|
|
||||||
if disable_result_object.valid:
|
|
||||||
logger.info(f"Success! We disabled the firewall correctly.")
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
error_msg = f"Firewall can't be disabled: {disable_result_object.message}"
|
|
||||||
logger.error(error_msg)
|
|
||||||
|
|
||||||
# if the systemwide_raiser didn't catch it with the reason, then..
|
|
||||||
raise ConnectionTerminationError(error_msg)
|
|
||||||
else:
|
|
||||||
logger.info("We are skipping disabling the firewall, because it's already off.")
|
|
||||||
|
|
||||||
|
|
||||||
# used in dead code at bottom:
|
|
||||||
# from core.services.networking.systemwide.dns_tools.process_dns_result import orchestrate_dns_check
|
|
||||||
|
|
||||||
# This is dead code right now
|
|
||||||
# def confirm_dns_is_reverted(wg_interface_name: str = 'wg'):
|
|
||||||
# do_they_even_use_systemd = dns.is_systemd_enabled()
|
|
||||||
|
|
||||||
# if not do_they_even_use_systemd:
|
|
||||||
# return True
|
|
||||||
|
|
||||||
# check_on_dns = orchestrate_dns_check(wg_interface_name)
|
|
||||||
|
|
||||||
# if check_on_dns.valid:
|
|
||||||
# logger.error("CRITICAL DNS PROBLEM! We turned WG off, but the DNS check shows it's still on. Trying again..")
|
|
||||||
# return False
|
|
||||||
# else:
|
|
||||||
# logger.info("We turned WG off, and the DNS check shows it reverted also. This is great.")
|
|
||||||
# return True
|
|
||||||
|
|
||||||
Loading…
Reference in a new issue