hosting/lib/wireguard.py

83 lines
3.5 KiB
Python
Raw Permalink Normal View History

2024-03-21 01:28:02 +00:00
from lib import logging as logging_lib
log = logging_lib.log
from lib import config as config_module
config = config_module.config
import os
def generate_config(container):
try:
if "name" in container and \
"wireguard" in container and \
"wireguard_private_key" in container and type(container["wireguard_private_key"])==str and \
"wireguard_address" in container and type(container["wireguard_address"])==str and \
"wireguard_peers" in container and type(container["wireguard_peers"])==list and \
"forward" in container and type(container["forward"]==list):
all_to_screen=[]
this_container_conf_dir = os.path.join(config.wireguard_config_folder, container["name"])
if not os.path.exists(os.path.join(this_container_conf_dir, "wg0.conf")):
os.makedirs(this_container_conf_dir, exist_ok=True)
for index, forward in enumerate(container["forward"]):
if "from" in forward and "to" in forward:
forward_code = f"""#!/bin/bash
while true
do
sleep 0.1
simpleproxy -R {forward['from']} -L {forward['to']}
done"""
file_path=os.path.join(this_container_conf_dir,f"forward{index}.sh")
with open(file_path, "w") as file:
file.write(forward_code)
# Apply chmod 750 (rwxr-x---) permissions to the file
os.chmod(file_path, 0o750)
all_to_screen.append(f"forward{index}.sh")
peers=''
for index, wireguard_peer in enumerate(container["wireguard_peers"]):
if "allowed_ips" in wireguard_peer:
reacheability_code=f"""#!/bin/bash
while true
do
sleep 1
ping {wireguard_peer["allowed_ips"].split('/')[0]} -i 2
done"""
file_path=os.path.join(this_container_conf_dir,f"conn_checker{index}.sh")
with open(file_path, "w") as file:
file.write(reacheability_code)
# Apply chmod 750 (rwxr-x---) permissions to the file
os.chmod(file_path, 0o750)
all_to_screen.append(f"conn_checker{index}.sh")
if "public_key" in wireguard_peer and "allowed_ips" in wireguard_peer:
endpoint=''
if(wireguard_peer["peer_endpoint"]):
endpoint=f"\nEndpoint = {wireguard_peer['peer_endpoint']}"
peers+=f"""\n[Peer]
PublicKey = {wireguard_peer["public_key"]}{endpoint}
AllowedIPs = {wireguard_peer["allowed_ips"]}"""
wg0=f"""[Interface]
Address = {container["wireguard_address"]}
ListenPort = {container["vpn_port"] if "vpn_port" in container else "51820"}
PrivateKey = {container["wireguard_private_key"]}{peers}"""
starter_sh="#!/bin/bash"
for index, script in enumerate(all_to_screen):
starter_sh+=f"\nscreen -dmS proc{index} /config/{script}"
starter_path=os.path.join(this_container_conf_dir,"proxy.sh")
with open(starter_path, "w") as file:
file.write(starter_sh)
# Apply chmod 750 (rwxr-x---) permissions to the file
os.chmod(starter_path, 0o750)
with open(os.path.join(this_container_conf_dir,"wg0.conf"), "w") as file:
file.write(wg0)
return True
except Exception as e:
return False