wireguardCreate 8.0 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. 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. # Main Function
  148. # =============
  149. # *************
  150. # =============
  151. # 1- Parse email/member id.
  152. # 2- Génère les clés wireguard.
  153. # 3- Crée/déploie la configuration wireguard.
  154. # 5- Envoie la clé à l'utilisateur (email/manuellement)
  155. if __name__ == '__main__':
  156. cp = configparser.ConfigParser()
  157. cp.read('/etc/wireguard/wg-create.ini')
  158. config = Config(cp)
  159. (member_email, member_id) = check_env()
  160. with tempfile.TemporaryDirectory() as temp_dir:
  161. print("[+] Génération des clés wireguard")
  162. (privkey_path, pubkey_path, psk_path) = gen_wg_keys(temp_dir)
  163. print("[+] Modification de la configuration wireguard")
  164. if not is_duplicate_entry_wg_conf(member_id, config_file):
  165. update_wg_config(member_id, config_file, pubkey_path, psk_path)
  166. else:
  167. print("Le membre {} semble déja avoir un compte VPN.".format(member_id))
  168. print("Veuillez contacter la liste de diffusion technique\
  169. si son compte necessite une ré-activation.")
  170. sys.exit(1)
  171. print("[+] Chargement de la nouvelle interface réseau")
  172. _run_cmd("systemctl restart %s" % (config.wg_service))
  173. print("[+] Envoi de la clé privée au nouveau membre")
  174. if use_email:
  175. with open(privkey_path, "r") as pkh:
  176. peer_privkey = pkh.read()
  177. with open(psk_path, "r") as pskh:
  178. peer_psk = pskh.read()
  179. email = Email(config.smtp_user, config.smtp_pass, config.smtp_from,\
  180. member_email, config.smtp_server)
  181. send_email(email, generate_wg_quick_client_config(peer_privkey, member_id, config.pubkey,\
  182. peer_psk, config.endpoint))
  183. else:
  184. print("Mode utilisateur avancé")
  185. print("=======================")
  186. print("À vous de vous débrouiller pour donner les clés/config à l'utilisateur")
  187. print("Clé privée: %s" % (privkey_path))
  188. print("Clé pré-partagée (psk): %s" % (psk_path))
  189. print("Clé publique (psk): %s" % (pubkey_path))
  190. input("Appuyez sur entrée pour continuer (les clés privées seront détruites): ")
  191. print("[+] Nettoyage des clés")
  192. _run_cmd("shred -u %s %s %s" % (privkey_path, pubkey_path, psk_path))
  193. print("[+] COMPTE CRÉE AVEC SUCCÈS")