Browse Source

Fixed pre-production related bugs.

Félix Baylac-Jacqué 6 years ago
parent
commit
73fae12cf4
2 changed files with 30 additions and 25 deletions
  1. 28 24
      create_new_wireguard_account
  2. 2 1
      wg-create-account.ini.sample

+ 28 - 24
create_new_wireguard_account

@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 
 import configparser
+import datetime
 import os
 import smtplib
 import subprocess
@@ -19,12 +20,13 @@ class Email:
 
     PS: I hate python.
     """
-    def __init__(self, username, passwd, from_addr, to_addr, server):
+    def __init__(self, username, passwd, from_addr, to_addr, server, port):
         self.username  = username
         self.passwd    = passwd
         self.from_addr = from_addr
         self.to_addr   = to_addr
         self.server    = server
+        self.port      = port
 
 class Config:
     """
@@ -34,13 +36,14 @@ class Config:
         self.smtp_user = config['smtp']['username']
         self.smtp_pass = config['smtp']['password']
         self.smtp_server = config['smtp']['server']
+        self.smtp_port = int(config['smtp']['port'])
         self.smtp_from = config['smtp']['from']
         self.wg_service = config['wireguard-service']['name']
         self.pubkey = config['wireguard-service']['pubkey']
         self.endpoint = config['wireguard-service']['endpoint']
 
 def _run_cmd(cmd):
-    print("$ %s" % (cmd))
+    print("> $ %s" % (cmd))
     subprocess.run(cmd, shell=True, check=True)
 
 def check_env ():
@@ -90,7 +93,7 @@ def is_duplicate_entry_wg_conf (member_id, config_file):
     only try to pattern match the ip addr.
     """
     with open(config_file, "r") as wg_conf_file:
-        return "10.0.0.{}".format(member_id) in wg_conf_file.read()
+        return ("10.0.0.{}".format(member_id) in wg_conf_file.read())
 
 def update_wg_config (member_id, config_file, pubkey_path, psk_path):
     """
@@ -98,18 +101,18 @@ def update_wg_config (member_id, config_file, pubkey_path, psk_path):
     """
     wg_new_peer = textwrap.dedent('''
     [Peer]
-    PublicKey = %PUBKEY%
-    PresharedKey = %PSK%
-    AllowedIPs = 10.0.0.{1}/24, fd00::{1}/64
+    PublicKey = pubksubs
+    PresharedKey = psksubs
+    AllowedIPs = 10.0.0.{0}/24, fd00::{0}/64
     ''').format(member_id)
     with open(config_file, "a") as wg_conf_file:
-        wg_conf_file.write(wg_config)
-    _run_cmd('sed -i "s/%PUBKEY%/$(cat %s)/" "%s"' % (pubkey_path, config_file))
-    _run_cmd('sed -i "s/%PSK%/$(cat %s)/" "%s"' % (psk_path, config_file))
+        wg_conf_file.write(wg_new_peer)
+    _run_cmd('sed -i "s|pubksubs|"$(cat %s)"|g" %s' % (pubkey_path, config_file))
+    _run_cmd('sed -i "s|psksubs|"$(cat %s)"|g" %s' % (psk_path, config_file))
 
 def generate_wg_quick_client_config(peer_priv_key, member_id,
                                     server_pub_key, psk, server_endpoint):
-    template = textwrap.dedent('''
+    return textwrap.dedent('''\
         [Interface]
         PrivateKey = {0}
         Address = 10.0.0.{1}/24, fd00::{1}/64
@@ -121,9 +124,10 @@ def generate_wg_quick_client_config(peer_priv_key, member_id,
         PresharedKey = {3}
         AllowedIPs = 0.0.0.0/0, ::/0
         Endpoint = {4}
-        ''').format(peer_priv_key, member_id, server_pub_key, psk, server_endpoint)
+        ''').format(peer_priv_key.strip(), member_id, server_pub_key, psk.strip(),\
+                    server_endpoint)
 
-def send_email(email, wgconfig_path):
+def send_email(email, wg_client_config):
     """
     Send the private key by email.
 
@@ -138,21 +142,19 @@ def send_email(email, wgconfig_path):
     password       = email.passwd
     msg            = MIMEMultipart()
     msg['Subject'] = "Votre acces VPN Baionet"
-    msg['Date']    = formatdate(localtime=True)
+    msg['Date']    = str(datetime.datetime.now())
     msg['From']    = email.from_addr
-    msg['To']      = [email.to_addr]
+    msg['To']      = email.to_addr
     body           = textwrap.dedent('''
     blahblah, cf le wiki blahblahblah
     ''')
-    msg.attach([MIMEText(body), MIMEText(config)])
-    with open(wg_client_path, "rb") as f:
-        part = MIMEApplication(
-                f.read(),
-                Name=os.path.basename(f))
-        part['Content-Disposition'] = 'attachment; filename=%s' % basename(f)
-        msg.attach(part)
+    part = MIMEApplication(
+            wg_client_config.encode("utf-8"),
+            Name="wg0.conf")
+    part['Content-Disposition'] = 'attachment; filename=wg0.conf'
+    msg.attach(part)
     username = email.username
-    server   = smtplib.SMTP(email.server)
+    server   = smtplib.SMTP(email.server, email.port)
     server.ehlo()
     server.starttls()
     server.login(email.username, email.passwd)
@@ -185,13 +187,15 @@ if __name__ == '__main__':
             print("")
             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.")
             use_email = input("Envoyer la configuration (contenant la clé privée) par email? (O/n)")
-            if use_email.strip().lower() == "o" :
+            if use_email.strip().lower() != "n" :
                 with open(privkey_path, "r") as pkh:
                    peer_privkey = pkh.read()
                 with open(psk_path, "r") as pskh:
                    peer_psk = pskh.read()
+                print("read files")
                 email = Email(config.smtp_user, config.smtp_pass, config.smtp_from,\
-                              member_email, config.smtp_server)
+                              member_email, config.smtp_server, config.smtp_port)
+                print("email created")
                 send_email(email, generate_wg_quick_client_config(peer_privkey, member_id, config.pubkey,\
                            peer_psk, config.endpoint))
             else:

+ 2 - 1
wg-create-account.ini.sample

@@ -2,9 +2,10 @@
 username = baionet
 password = pass
 server = smtp.example.org
+port = 42
 from = from@example.org
 
 [wireguard-service]
 name = wg-quick@wg0.service
 pubkey = wg_server_interface_pubkey
-endpoint = 0.0.0.0:0000 
+endpoint = 0.0.0.0:0000