wireguardCreate.py 7.7 KB

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