Queer European MD passionate about IT
Browse Source

Working on SSL certificate generation

Davte 5 years ago
parent
commit
557363d3de
2 changed files with 69 additions and 16 deletions
  1. 9 13
      README.md
  2. 60 3
      filebridging/create_certificate.py

+ 9 - 13
README.md

@@ -60,12 +60,19 @@ python -m filebridging.client --help
 
 
 ## Generating SSL certificates
 ## Generating SSL certificates
 
 
+You may use `filebridging.create_certificate.py` script or use openssl from the command line.
 
 
+###Via script
+```bash
+python -m filebridging.create_certificate --name example --domain example.com --force
+```
+
+### Via command line
 Store configuration in file `mycert.csr.cnf` and run the following command to generate a self-signed SSL certificate.
 Store configuration in file `mycert.csr.cnf` and run the following command to generate a self-signed SSL certificate.
 ```bash
 ```bash
 openssl req -newkey rsa:4096 -nodes -keyout ./mycert.key \
 openssl req -newkey rsa:4096 -nodes -keyout ./mycert.key \
- -x509 -days 365 -out ./mycert.crt -extensions req_ext \
- -config <( cat mycert.csr.cnf )
+ -x509 -days 365 -out ./mycert.crt \
+ -config mycert.csr.cnf
 ```
 ```
 
 
 
 
@@ -76,18 +83,7 @@ default_bits = 4096
 prompt = no
 prompt = no
 default_md = sha256
 default_md = sha256
 distinguished_name = dn
 distinguished_name = dn
-req_extensions = req_ext
-
-[ req_ext ]
-basicConstraints = CA:FALSE
-keyUsage = nonRepudiation, digitalSignature, keyEncipherment
-subjectAltName = @alt_names
 
 
 [ dn ]
 [ dn ]
 CN = yourdomain.com
 CN = yourdomain.com
-
-[ alt_names ]
-DNS.1 = yourdomain.com
-DNS.2 = 1.111.111.11
-DNS.3 = https://www.yourdomain.com
 ```
 ```

+ 60 - 3
filebridging/create_certificate.py

@@ -6,6 +6,7 @@ Requirements: OpenSSL.
 import argparse
 import argparse
 import logging
 import logging
 import os
 import os
+import subprocess
 
 
 
 
 def get_paths(path):
 def get_paths(path):
@@ -17,6 +18,19 @@ def get_paths(path):
 
 
 
 
 def main():
 def main():
+    # noinspection SpellCheckingInspection
+    log_formatter = logging.Formatter(
+        "%(asctime)s [%(module)-15s %(levelname)-8s]     %(message)s",
+        style='%'
+    )
+    root_logger = logging.getLogger()
+    root_logger.setLevel(logging.DEBUG)
+
+    console_handler = logging.StreamHandler()
+    console_handler.setFormatter(log_formatter)
+    console_handler.setLevel(logging.DEBUG)
+    root_logger.addHandler(console_handler)
+
     cli_parser = argparse.ArgumentParser(description='Create SSL certificate',
     cli_parser = argparse.ArgumentParser(description='Create SSL certificate',
                                          allow_abbrev=False)
                                          allow_abbrev=False)
     cli_parser.add_argument('-n', '--name',
     cli_parser.add_argument('-n', '--name',
@@ -24,6 +38,11 @@ def main():
                             default=None,
                             default=None,
                             required=False,
                             required=False,
                             help='Certificate, key and configuration file name')
                             help='Certificate, key and configuration file name')
+    cli_parser.add_argument('-d', '--domain',
+                            type=str,
+                            default=None,
+                            required=False,
+                            help='Server domain (e.g. example.com)')
     cli_parser.add_argument('-f', '--force', '--overwrite',
     cli_parser.add_argument('-f', '--force', '--overwrite',
                             action='store_true',
                             action='store_true',
                             help='Overwrite certificate and key if they exist')
                             help='Overwrite certificate and key if they exist')
@@ -34,8 +53,8 @@ def main():
             from config import name
             from config import name
         except ImportError:
         except ImportError:
             name = None
             name = None
-    while name is None or not os.access(os.path.dirname(os.path.abspath(name)),
-                                        os.W_OK):
+    while not name or not os.access(os.path.dirname(os.path.abspath(name)),
+                                    os.W_OK):
         try:
         try:
             name = input(
             name = input(
                 "Enter a valid file name for certificate, key and "
                 "Enter a valid file name for certificate, key and "
@@ -62,7 +81,45 @@ def main():
     ).lower().startswith('y'):
     ).lower().startswith('y'):
         logging.error("Interrupted. Provide a different --name.")
         logging.error("Interrupted. Provide a different --name.")
         return
         return
-    print(certificate_path)
+    domain = arguments['domain']
+    if domain is None:
+        try:
+            from config import domain
+        except ImportError:
+            domain = None
+    while not domain:
+        domain = input("Enter server domain (e.g. example.com)\n\t\t")
+    with open(configuration_path, 'w') as configuration_file:
+        logging.info("Writing configuration file...")
+        configuration_file.write(
+            "[req]\n"
+            "default_bits = 4096\n"
+            "prompt = no\n"
+            "default_md = sha256\n"
+            "distinguished_name = dn\n"
+            "\n"
+            "[dn]\n"
+            f"CN = {domain}\n"
+        )
+    logging.info("Generating certificate and key...")
+    subprocess.run(
+        [
+            f"openssl req -newkey rsa:4096 -nodes "
+            f"-keyout \"{key_path}\" -x509 -days 365 "
+            f"-out \"{certificate_path}\" "
+            f"-config \"{configuration_path}\""
+        ],
+        capture_output=True,
+        text=True,
+        shell=True
+    )
+    with open(certificate_path, 'r') as certificate_file:
+        logging.info(
+            "Certificate:\n\n{certificate}".format(
+                certificate=''.join(certificate_file.readlines())
+            ),
+        )
+    logging.info("Done!")
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':