wireguardCreate 7.8 KB

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