DeaD_EyE

gen_tor_client_auth

Jan 29th, 2022 (edited)
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. https://tor.stackexchange.com/questions/19221/how-to-setup-client-authorization-for-v3-onion-services
  5. https://github.com/AnarchoTechNYC/meta/wiki/Connecting-to-an-authenticated-Onion-service#procedure-for-version-3-onion-services
  6.  
  7. Python-Script from AnarchoTechNYC:
  8. https://github.com/AnarchoTechNYC/ansible-role-tor/blob/master/molecule/default/scripts/tor-auth-x25519-gen.py
  9. """
  10.  
  11.  
  12. from base64 import b32encode, b64decode
  13. from pathlib import Path
  14. from subprocess import run
  15. from tempfile import TemporaryDirectory
  16. from typing import NamedTuple
  17. from urllib.parse import urlparse
  18.  
  19.  
  20. class ClientAuth(NamedTuple):
  21.     private: str
  22.     public: str
  23.  
  24.  
  25. def gen_client_keypair(onion_url: str) -> ClientAuth:
  26.  
  27.     host = urlparse(onion_url).hostname
  28.     if host is None or not host.endswith(".onion"):
  29.         raise ValueError("Only onion urls can use tor client auth")
  30.     else:
  31.         host, _ = host.split(".", maxsplit=1)
  32.  
  33.     with TemporaryDirectory() as directory:
  34.         private_key = Path(directory, "private-key.pem")
  35.         public_key = Path(directory, "public-key.pem")
  36.         run(["openssl", "genpkey", "-algorithm", "x25519", "-out", private_key])
  37.         run(
  38.             [
  39.                 "openssl",
  40.                 "pkey",
  41.                 "-in",
  42.                 private_key,
  43.                 "-pubout",
  44.                 "-outform",
  45.                 "PEM",
  46.                 "-out",
  47.                 public_key,
  48.             ]
  49.         )
  50.         private_key = b32encode(
  51.             b64decode(private_key.read_text().splitlines()[1])
  52.         ).decode()[:-4]
  53.         public_key = b32encode(
  54.             b64decode(public_key.read_text().splitlines()[1])
  55.         ).decode()[:-4]
  56.         return ClientAuth(
  57.             f"{host}:x25519:{private_key}",
  58.             f"descriptor:x25519:{public_key}",
  59.         )
  60.  
  61.  
  62. onion_url = input("Onion-URL: ")
  63. try:
  64.     key_pair = gen_client_keypair(onion_url)
  65. except ValueError as e:
  66.     raise SystemExit(e.args[0])
  67.  
  68. with (
  69.     open("client.auth_private", "w") as fd_priv,
  70.     open("client.auth", "w") as fd_pub,
  71. ):
  72.     fd_priv.write(key_pair.private)
  73.     fd_pub.write(key_pair.private)
  74.  
  75. print("Saved keys as `client.auth_private` and `client.auth`")
  76. print("client.auth_private:", key_pair.private)
  77. print("client.auth: ", key_pair.public)
  78.  
Add Comment
Please, Sign In to add comment