Created
August 14, 2024 15:45
-
-
Save kray74/b4b9082a8cf489352604b6d7a25c49df to your computer and use it in GitHub Desktop.
Convert amnezia wireguard vpn key to wireguard config file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys | |
import base64 | |
import zlib | |
import json | |
from typing import Any | |
def decode_vpn_key(link: str) -> dict[str, Any]: | |
vpn_prefix = "vpn://" | |
zlib_header_size = 4 | |
assert(link.startswith(vpn_prefix)) | |
# strip vpn:// prefix and append base64 padding characters | |
# length of base64 string must be multiple of 3, | |
# so 2 paddding characters will be enough. | |
# Python ignores *extra* padding characters | |
link = link[len(vpn_prefix):] + "==" | |
compressed_data: bytes = base64.urlsafe_b64decode(link) | |
assert(len(compressed_data) > zlib_header_size) | |
# strip zlib header | |
compressed_data = compressed_data[zlib_header_size:] | |
return json.loads(zlib.decompress(compressed_data)) | |
def parse_awg_config(input_json: dict[str, Any]) -> str: | |
dns1: str = input_json["dns1"] | |
dns2: str = input_json["dns2"] | |
last_config: str | |
container_name: str = input_json["defaultContainer"] | |
for container in input_json["containers"]: | |
if container["container"] == container_name: | |
last_config = container["awg"]["last_config"] | |
break | |
assert(last_config) | |
# last_config is a JSON itself | |
wg_config: str = json.loads(last_config)["config"] | |
return wg_config.replace("$PRIMARY_DNS", dns1).replace("$SECONDARY_DNS", dns2) | |
def main(): | |
# The instructions will be printed to stderr, | |
# and the awg configuration itself - to stdout. | |
# This allows you to use shell redirection: | |
# ./awg-key-to-conf.py > wg0.conf | |
# Avoid providing the VPN key as a command line argument! | |
# Because it will be stored in the commands history | |
print("Enter your VPN key (vpn://...):", file=sys.stderr) | |
vpn_key = input() | |
json = decode_vpn_key(vpn_key) | |
cfg = parse_awg_config(json) | |
if sys.stdout.isatty(): | |
print("\nYour AWG config:", file=sys.stderr) | |
else: | |
print("\nYour AWG config stored to the standard output", file=sys.stderr) | |
print(cfg) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment