| 1 |
12b255b |
Dawsh |
2y ago |
import ssl |
| 2 |
12b255b |
Dawsh |
2y ago |
|
| 3 |
a47eb4c |
Dawsh |
2y ago |
from cryptography import x509 |
| 4 |
a47eb4c |
Dawsh |
2y ago |
from cryptography.hazmat.backends import default_backend |
| 5 |
a47eb4c |
Dawsh |
2y ago |
from OpenSSL import crypto |
| 6 |
a47eb4c |
Dawsh |
2y ago |
|
| 7 |
a47eb4c |
Dawsh |
2y ago |
|
| 8 |
a47eb4c |
Dawsh |
2y ago |
def get_cert_SANs(cert: bytes): |
| 9 |
a47eb4c |
Dawsh |
2y ago |
cert = x509.load_pem_x509_certificate(cert, default_backend()) |
| 10 |
a47eb4c |
Dawsh |
2y ago |
san_list = [] |
| 11 |
a47eb4c |
Dawsh |
2y ago |
for extension in cert.extensions: |
| 12 |
a47eb4c |
Dawsh |
2y ago |
if isinstance(extension.value, x509.SubjectAlternativeName): |
| 13 |
a47eb4c |
Dawsh |
2y ago |
san = extension.value |
| 14 |
a47eb4c |
Dawsh |
2y ago |
for name in san: |
| 15 |
a47eb4c |
Dawsh |
2y ago |
san_list.append(name.value) |
| 16 |
a47eb4c |
Dawsh |
2y ago |
return san_list |
| 17 |
a47eb4c |
Dawsh |
2y ago |
|
| 18 |
a47eb4c |
Dawsh |
2y ago |
|
| 19 |
a47eb4c |
Dawsh |
2y ago |
def generate_certificate(): |
| 20 |
a47eb4c |
Dawsh |
2y ago |
k = crypto.PKey() |
| 21 |
a47eb4c |
Dawsh |
2y ago |
k.generate_key(crypto.TYPE_RSA, 4096) |
| 22 |
a47eb4c |
Dawsh |
2y ago |
cert = crypto.X509() |
| 23 |
a47eb4c |
Dawsh |
2y ago |
cert.get_subject().CN = "Gozargah" |
| 24 |
a47eb4c |
Dawsh |
2y ago |
cert.gmtime_adj_notBefore(0) |
| 25 |
01cdf2e |
Dawsh |
2y ago |
cert.gmtime_adj_notAfter(100 * 365 * 24 * 60 * 60) |
| 26 |
a47eb4c |
Dawsh |
2y ago |
cert.set_issuer(cert.get_subject()) |
| 27 |
a47eb4c |
Dawsh |
2y ago |
cert.set_pubkey(k) |
| 28 |
01cdf2e |
Dawsh |
2y ago |
cert.sign(k, "sha512") |
| 29 |
a47eb4c |
Dawsh |
2y ago |
cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8") |
| 30 |
a47eb4c |
Dawsh |
2y ago |
key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8") |
| 31 |
a47eb4c |
Dawsh |
2y ago |
|
| 32 |
01cdf2e |
Dawsh |
2y ago |
return {"cert": cert_pem, "key": key_pem} |
| 33 |
12b255b |
Dawsh |
2y ago |
|
| 34 |
12b255b |
Dawsh |
2y ago |
|
| 35 |
12b255b |
Dawsh |
2y ago |
def create_secure_context( |
| 36 |
01cdf2e |
Dawsh |
2y ago |
client_cert: str, |
| 37 |
01cdf2e |
Dawsh |
2y ago |
client_key: str, |
| 38 |
01cdf2e |
Dawsh |
2y ago |
trusted: str, |
| 39 |
12b255b |
Dawsh |
2y ago |
) -> ssl.SSLContext: |
| 40 |
12b255b |
Dawsh |
2y ago |
ctx = ssl.create_default_context(cafile=trusted) |
| 41 |
12b255b |
Dawsh |
2y ago |
ctx.load_cert_chain(client_cert, client_key) |
| 42 |
01cdf2e |
Dawsh |
2y ago |
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20") |
| 43 |
01cdf2e |
Dawsh |
2y ago |
ctx.set_alpn_protocols(["h2"]) |
| 44 |
12b255b |
Dawsh |
2y ago |
ctx.check_hostname = False |
| 45 |
12b255b |
Dawsh |
2y ago |
ctx.verify_mode = ssl.CERT_NONE |
| 46 |
12b255b |
Dawsh |
2y ago |
return ctx |