| 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 |
a47eb4c |
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 |
a47eb4c |
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 |
a47eb4c |
Dawsh |
2y ago |
return { |
| 33 |
a47eb4c |
Dawsh |
2y ago |
"cert": cert_pem, |
| 34 |
a47eb4c |
Dawsh |
2y ago |
"key": key_pem |
| 35 |
a47eb4c |
Dawsh |
2y ago |
} |
| 36 |
12b255b |
Dawsh |
2y ago |
|
| 37 |
12b255b |
Dawsh |
2y ago |
|
| 38 |
12b255b |
Dawsh |
2y ago |
def create_secure_context( |
| 39 |
12b255b |
Dawsh |
2y ago |
client_cert: str, client_key: str, trusted: str, |
| 40 |
12b255b |
Dawsh |
2y ago |
) -> ssl.SSLContext: |
| 41 |
12b255b |
Dawsh |
2y ago |
ctx = ssl.create_default_context(cafile=trusted) |
| 42 |
12b255b |
Dawsh |
2y ago |
ctx.load_cert_chain(client_cert, client_key) |
| 43 |
12b255b |
Dawsh |
2y ago |
ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20') |
| 44 |
12b255b |
Dawsh |
2y ago |
ctx.set_alpn_protocols(['h2']) |
| 45 |
12b255b |
Dawsh |
2y ago |
ctx.check_hostname = False |
| 46 |
12b255b |
Dawsh |
2y ago |
ctx.verify_mode = ssl.CERT_NONE |
| 47 |
12b255b |
Dawsh |
2y ago |
return ctx |