ssl_context.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import ssl
  2. def load_ssl_context(cert_file, pkey_file):
  3. context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  4. context.load_cert_chain(cert_file, pkey_file)
  5. return context
  6. def save_ssl_files(cert, pkey):
  7. import atexit
  8. import os
  9. import tempfile
  10. from cryptography.hazmat.primitives import serialization
  11. cert_handle, cert_file = tempfile.mkstemp()
  12. pkey_handle, pkey_file = tempfile.mkstemp()
  13. atexit.register(os.remove, pkey_file)
  14. atexit.register(os.remove, cert_file)
  15. os.write(cert_handle, cert.public_bytes(serialization.Encoding.PEM))
  16. os.write(
  17. pkey_handle,
  18. pkey.private_bytes(
  19. encoding=serialization.Encoding.PEM,
  20. format=serialization.PrivateFormat.TraditionalOpenSSL,
  21. encryption_algorithm=serialization.NoEncryption(),
  22. ),
  23. )
  24. os.close(cert_handle)
  25. os.close(pkey_handle)
  26. return cert_file, pkey_file
  27. def generate_ssl_pair(host):
  28. try:
  29. from cryptography import x509
  30. from cryptography.x509.oid import NameOID
  31. from cryptography.hazmat.primitives import hashes
  32. from cryptography.hazmat.primitives.asymmetric import rsa
  33. import datetime
  34. except ImportError:
  35. raise TypeError(
  36. "Using ad-hoc certificates requires the cryptography library."
  37. ) from None
  38. cn = f"*.{host}/CN={host}"
  39. pkey = rsa.generate_private_key(public_exponent=65537, key_size=2048)
  40. subject = x509.Name(
  41. [
  42. x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"),
  43. x509.NameAttribute(NameOID.COMMON_NAME, cn),
  44. ]
  45. )
  46. one_day = datetime.timedelta(1, 0, 0)
  47. cert = (
  48. x509.CertificateBuilder()
  49. .subject_name(subject)
  50. .issuer_name(subject)
  51. .public_key(pkey.public_key())
  52. .serial_number(x509.random_serial_number())
  53. .not_valid_before(datetime.datetime.today() - one_day)
  54. .not_valid_after(datetime.datetime.today() + (one_day * 365))
  55. .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False)
  56. .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False)
  57. .sign(private_key=pkey, algorithm=hashes.SHA256())
  58. )
  59. return save_ssl_files(cert, pkey)