create_new_wireguard_account 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #!/usr/bin/env python3
  2. import configparser
  3. import os
  4. import smtplib
  5. import subprocess
  6. import sys
  7. import tempfile
  8. import textwrap
  9. from email.mime.multipart import MIMEMultipart
  10. from email.mime.application import MIMEApplication
  11. from email.mime.text import MIMEText
  12. class Email:
  13. """
  14. Not really necessary, but I keep on forgetting most of an email arguments
  15. and I'm tired of debugging this class of error... Too bad we don't have any
  16. record type in this language.
  17. PS: I hate python.
  18. """
  19. def __init__(self, username, passwd, from_addr, to_addr, server):
  20. self.username = username
  21. self.passwd = passwd
  22. self.from_addr = from_addr
  23. self.to_addr = to_addr
  24. self.server = server
  25. class Config:
  26. """
  27. Same as Email
  28. """
  29. def __init__(self, config):
  30. self.smtp_user = config['smtp']['username']
  31. self.smtp_pass = config['smtp']['password']
  32. self.smtp_server = config['smtp']['server']
  33. self.smtp_from = config['smtp']['from']
  34. self.wg_service = config['wireguard-service']['name']
  35. self.pubkey = config['wireguard-service']['pubkey']
  36. self.endpoint = config['wireguard-service']['endpoint']
  37. def _run_cmd(cmd):
  38. print("$ %s" % (cmd))
  39. subprocess.run(cmd, shell=True, check=True)
  40. def check_env ():
  41. """
  42. Checks if wireguard is correctly installed, the script is run as
  43. root and the member id is correct.
  44. """
  45. wgInstalled = os.system("wg")
  46. if os.geteuid() != 0:
  47. print("On a besoin des droits root pour créer un accès VPN.")
  48. print("Relancez la commande préfixée d'un sudo.")
  49. raise Exception("Got root?")
  50. if wgInstalled != 0:
  51. print("Wireguard ne semble pas être installé sur votre système.")
  52. print("Il faudrait installer wireguard-tools et wireguard-dkms avant\
  53. d'utiliser ce script")
  54. raise Exception("Install wg")
  55. member_email = input("EMail du nouveau membre: ")
  56. member_id = int(input("Numéro d'adhérant du nouveau membre: "))
  57. if member_id < 2 or member_id > 253:
  58. print("On est parti du principe que les IDs des membres commencent à 1.")
  59. print("Ah, aussi, pour le moment, on est aussi partis du principe que ça \
  60. s'arrête à 253.")
  61. print("Si on a plus de 253 membres, premièrement, FÉLICITATIONS venant \
  62. du Félix du passé. Par contre, il faut repenser l'adressage des \
  63. IPs du VPN maintenant :( Ranson du succès j'immagine.")
  64. raise Exception("Wrong member_id")
  65. return (member_email, member_id)
  66. def gen_wg_keys (temp_dir):
  67. """
  68. Generates both the private and the public wireguard key of the new member.
  69. """
  70. pubkey_path = os.path.join(temp_dir, "pub.key")
  71. privkey_path = os.path.join(temp_dir, "priv.key")
  72. psk_path = os.path.join(temp_dir, "psk.key")
  73. _run_cmd("wg genkey | tee %s | wg pubkey > %s" % (privkey_path, pubkey_path))
  74. _run_cmd("wg genpsk > %s" % (psk_path))
  75. return (privkey_path, pubkey_path, psk_path)
  76. def is_duplicate_entry_wg_conf (member_id, config_file):
  77. """
  78. Look for a potential wireguard duplicate entry.
  79. Note: wg config format is not really a init file because of the multiple
  80. init entries. Hence, we cannot use a proper parser to to the check. We'll
  81. only try to pattern match the ip addr.
  82. """
  83. with open(config_file, "r") as wg_conf_file:
  84. return "10.0.0.{}".format(member_id) in wg_conf_file.read()
  85. def update_wg_config (member_id, config_file, pubkey_path, psk_path):
  86. """
  87. Generate the wireguard peer entry for this new member.
  88. """
  89. wg_new_peer = textwrap.dedent('''
  90. [Peer]
  91. PublicKey = %PUBKEY%
  92. PresharedKey = %PSK%
  93. AllowedIPs = 10.0.0.{1}/24, fd00::{1}/64
  94. ''').format(member_id)
  95. with open(config_file, "a") as wg_conf_file:
  96. wg_conf_file.write(wg_config)
  97. _run_cmd('sed -i "s/%PUBKEY%/$(cat %s)/" "%s"' % (pubkey_path, config_file))
  98. _run_cmd('sed -i "s/%PSK%/$(cat %s)/" "%s"' % (psk_path, config_file))
  99. def generate_wg_quick_client_config(peer_priv_key, member_id,
  100. server_pub_key, psk, server_endpoint):
  101. template = textwrap.dedent('''
  102. [Interface]
  103. PrivateKey = {0}
  104. Address = 10.0.0.{1}/24, fd00::{1}/64
  105. SaveConfig = false
  106. DNS = 80.67.169.12, 80.67.169.40, 2001:910:800::12, 2001:910:800::40
  107. [Peer]
  108. PublicKey = {2}
  109. PresharedKey = {3}
  110. AllowedIPs = 0.0.0.0/0, ::/0
  111. Endpoint = {4}
  112. ''').format(peer_priv_key, member_id, server_pub_key, psk, server_endpoint)
  113. def send_mail(email, wgconfig_path):
  114. """
  115. Send the private key by email.
  116. email:
  117. - username
  118. - passwd
  119. - from_addr
  120. - to_addr
  121. - server
  122. """
  123. from_addr = 'bureau@baionet.fr'
  124. password = email.passwd
  125. msg = MIMEMultipart()
  126. msg['Subject'] = "Votre acces VPN Baionet"
  127. msg['Date'] = formatdate(localtime=True)
  128. msg['From'] = email.from_addr
  129. msg['To'] = [email.to_addr]
  130. body = textwrap.dedent('''
  131. blahblah, cf le wiki blahblahblah
  132. ''')
  133. msg.attach([MIMEText(body), MIMEText(config)])
  134. with open(wg_client_path, "rb") as f:
  135. part = MIMEApplication(
  136. f.read(),
  137. Name=os.path.basename(f))
  138. part['Content-Disposition'] = 'attachment; filename=%s' % basename(f)
  139. msg.attach(part)
  140. username = email.username
  141. server = smtplib.SMTP(email.server)
  142. server.ehlo()
  143. server.starttls()
  144. server.login(email.username, email.passwd)
  145. server.sendmail(email.from_addr, email.to_addr, msg.as_string())
  146. server.quit()
  147. print("[+] E-Mail envoyé à %s." % email.to_addr)
  148. # Main Function
  149. # =============
  150. # *************
  151. # =============
  152. # 1- Parse email/member id.
  153. # 2- Génère les clés wireguard.
  154. # 3- Crée/déploie la configuration wireguard.
  155. # 5- Envoie la clé à l'utilisateur (email/manuellement)
  156. if __name__ == '__main__':
  157. cp = configparser.ConfigParser()
  158. cp.read('/etc/wireguard/wg-create.ini')
  159. config = Config(cp)
  160. (member_email, member_id) = check_env()
  161. with tempfile.TemporaryDirectory() as temp_dir:
  162. try:
  163. print("[+] Génération des clés wireguard")
  164. (privkey_path, pubkey_path, psk_path) = gen_wg_keys(temp_dir)
  165. print("[+] Envoi de la clé privée au nouveau membre")
  166. print("Deux solutions ici:")
  167. print("1- On envoie la configuration du nouveau membre en ligne. (automatique)")
  168. print("2- On utilise une autre méthode pour passer la configuration au nouveau membre. (manuel)")
  169. print("")
  170. print("Suivant votre modèle de menace, envoyer la clé privée par e-mail peut ou peut ne pas être une bonne idée.")
  171. use_email = input("Envoyer la configuration (contenant la clé privée) par email? (O/n)")
  172. if use_email.strip().lower() == "o" :
  173. with open(privkey_path, "r") as pkh:
  174. peer_privkey = pkh.read()
  175. with open(psk_path, "r") as pskh:
  176. peer_psk = pskh.read()
  177. email = Email(config.smtp_user, config.smtp_pass, config.smtp_from,\
  178. member_email, config.smtp_server)
  179. send_email(email, generate_wg_quick_client_config(peer_privkey, member_id, config.pubkey,\
  180. peer_psk, config.endpoint))
  181. else:
  182. print("Mode utilisateur avancé")
  183. print("=======================")
  184. print("À vous de vous débrouiller pour passer les clés/config à l'utilisateur")
  185. print("Clé privée: %s" % (privkey_path))
  186. print("Clé pré-partagée (psk): %s" % (psk_path))
  187. print("Clé publique (psk): %s" % (pubkey_path))
  188. input("Appuyez sur entrée pour continuer (les clés privées seront détruites): ")
  189. except Exception as e:
  190. print("ERREUR: erreur lors de la génération/transfert de la clé:")
  191. print(e)
  192. print("Si vous ne comprenez pas le problème, transférez le message d'erreur complet à la liste\
  193. de diffusion technique.")
  194. print("Pas de panique: on n'a pas touché à la configuration du serveur de wireguard, \
  195. rien n'a cassé.")
  196. try:
  197. print("[+] Modification de la configuration wireguard")
  198. if not is_duplicate_entry_wg_conf(member_id, config_file):
  199. update_wg_config(member_id, config_file, pubkey_path, psk_path)
  200. else:
  201. print("Le membre {} semble déja avoir un compte VPN.".format(member_id))
  202. print("Veuillez contacter la liste de diffusion technique\
  203. si son compte necessite une ré-activation.")
  204. sys.exit(1)
  205. print("[+] Chargement de la nouvelle interface réseau")
  206. _run_cmd("systemctl restart %s" % (config.wg_service))
  207. print("[+] Nettoyage des clés")
  208. _run_cmd("shred -u %s %s %s" % (privkey_path, pubkey_path, psk_path))
  209. print("[+] COMPTE CRÉE AVEC SUCCÈS")
  210. except Exception as e:
  211. print("ERREUR CRITIQUE: attention, la configuration wireguard est cassée, il y a probablement urgence.")
  212. print(e)
  213. print("Si vous ne savez pas quoi faire pour régler le problème, contactez en urgence la\
  214. liste de diffusion technique en joignant le message d'erreur ci-dessus.")
  215. print("Je le répète: le serveur VPN est probablement cassé, c'est une urgence.")