-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_selfsigned.py
More file actions
executable file
·171 lines (165 loc) · 7.51 KB
/
script_selfsigned.py
File metadata and controls
executable file
·171 lines (165 loc) · 7.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# -*- coding: utf-8 -*-
import logging
from pathlib import Path
import requests
import subprocess
from sys import exit
# Error handling
FORMAT = "%(asctime)s |%(levelname)s |%(message)s"
logging.basicConfig(level=logging.WARNING,filename="selfsigned.log",filemode="a",format=FORMAT)
# Signing certificate
class SelfSignedCertificate():
# Configuration
def __init__(self):
# Backup IP address, if you really want
self.Address4Backup = ""
self.Address6Backup = ""
# CSR config
self.Days = 365
self.Country = "JP"
self.State = "Tokyo Metropolis"
self.Locality = "Toshima"
self.Organization = "Tsukinomori Girl's Academy"
self.Unit = "Concert Band Club"
# Certificate folder path, None as default path
self.CertFolder = None
# Certificate and private key name
self.Certificate = "selfsigned_certificate.crt"
self.PrivateKey = "selfsigned_certificate.key"
# Server command
self.WebServer = None
# Default path
self.ConfigFolder = Path.cwd()
self.CSRConfig = "selfsigned_certificate.conf"
# IP address checker
self.IpIfy4 = "https://api.ipify.org?format=json"
self.IpIfy6 = "https://api64.ipify.org/?format=json"
# Check IP address
def LocalAddressCheck4(self):
try:
with requests.get(self.IpIfy4,timeout=30) as AddressCheck4:
if AddressCheck4.status_code == 200:
AddressCheck4JSON = AddressCheck4.json()
return AddressCheck4JSON.get("ip") or None
else:
logging.error(f"Unable get IPv4 address |{AddressCheck4.status_code}")
return None
except Exception as AddressCheck4Error:
logging.error(f"Unable get IPv4 address |{AddressCheck4Error}")
return None
def LocalAddressCheck6(self):
try:
with requests.get(self.IpIfy6,timeout=30) as AddressCheck6:
if AddressCheck6.status_code == 200:
AddressCheck6JSON = AddressCheck6.json()
return AddressCheck6JSON.get("ip") or None
else:
logging.error(f"Unable get IPv6 address |{AddressCheck6.status_code}")
return None
except Exception as AddressCheck6Error:
logging.error(f"Unable get IPv6 address |{AddressCheck6Error}")
return None
# Certificate Signing Request Config
def CreateCSR(self,Address4,Address6):
try:
CSRConfig4 = f"IP.1 = {Address4}" if isinstance(Address4,str) and Address4.strip() else self.Address4Backup
CSRConfig6 = f"IP.2 = {Address6}" if isinstance(Address6,str) and Address6.strip() else self.Address6Backup
CSRConfigContents = [
"[req]",
"default_bits = 2048",
"default_md = sha256",
"utf8 = yes",
"string_mask = utf8only",
"prompt = no",
"req_extensions = x509_v3_req",
"distinguished_name = req_distinguished_name",
"[x509_v3_req]",
"basicConstraints = CA:FALSE",
"keyUsage = digitalSignature, keyEncipherment",
"extendedKeyUsage = serverAuth",
"subjectAltName = @alt_names",
"[alt_names]",
"DNS.1 = localhost",
CSRConfig4,
CSRConfig6,
"[req_distinguished_name]",
f"countryName = {self.Country}",
f"stateOrProvinceName = {self.State}",
f"localityName = {self.Locality}",
f"organizationName = {self.Organization}",
f"organizationalUnitName = {self.Unit}",
"commonName = localhost"
]
# CSR config
CSRConfigFile = self.ConfigFolder / self.CSRConfig
with CSRConfigFile.open("w",encoding="utf-8") as CSRSignConfig:
# Drop empty configuration string
for CSRConfigLine in filter(None,CSRConfigContents):
CSRSignConfig.write(CSRConfigLine + "\n")
except Exception as CreateCSRError:
raise RuntimeError(f"Unable create CSR Configuration file |{CreateCSRError}")
# Create Certificate
def CertificateSigning(self):
# CSR path
CSRConfigFile = self.ConfigFolder / self.CSRConfig
if not CSRConfigFile.exists():
raise RuntimeError("Cannot found CSR configuration file")
# Certificate path
if self.CertFolder is None or not str(self.CertFolder).strip():
CertificatesDIR = self.ConfigFolder
elif isinstance(self.CertFolder,str):
CertificatesDIR = Path(self.CertFolder)
elif isinstance(self.CertFolder,Path):
CertificatesDIR = self.CertFolder
else:
raise RuntimeError("CSR configuration file path error")
CertificatesDIR.mkdir(parents=True,exist_ok=True)
KeyoutFileStr = str(CertificatesDIR / self.PrivateKey)
CertificateFileStr = str(CertificatesDIR / self.Certificate)
CSRConfigFileStr = str(CSRConfigFile)
# OpenSSL generate command
OpensslCommand = ["openssl","req","-x509","-new",
"-nodes","-sha256","-utf8","-days",f"{self.Days}","-newkey","rsa:2048",
"-keyout",f"{KeyoutFileStr}","-out",f"{CertificateFileStr}","-config",f"{CSRConfigFileStr}",
"-extensions","x509_v3_req"]
# Generate certificate
try:
OpenSSLStatus = subprocess.Popen(OpensslCommand,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
stdout,stderr = OpenSSLStatus.communicate()
if OpenSSLStatus.returncode != 0:
raise RuntimeError(f"Error occurred during certificate and private key |{stdout} |{stderr}")
# Cleanup config
CSRConfigFile.unlink()
except Exception as CertificateSigningRequestError:
logging.exception(CertificateSigningRequestError)
raise RuntimeError(f"Unbale create certificate and private key |{CertificateSigningRequestError}")
# Server reload
if self.WebServer is not None and isinstance(self.WebServer,list):
try:
ServerStatus = subprocess.Popen(
self.WebServer,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
# Discard output
stdout,stderr = ServerStatus.communicate()
# Check if command unsuccessful
if ServerStatus.returncode != 0:
raise RuntimeError(f"Error occurred during server reload/restart |{stdout} |{stderr}")
except Exception as ServerReloadError:
raise RuntimeError(f"Error occurred during server reload/restart |{ServerReloadError}")
# Runtime
try:
SelfSignCa = SelfSignedCertificate()
Address4 = SelfSignCa.LocalAddressCheck4()
Address6 = SelfSignCa.LocalAddressCheck6()
# Unable get IPv6 / IPv4 only env
if Address4 == Address6:
Address6 = None
# Create CSR config
SelfSignCa.CreateCSR(Address4,Address6)
# Create Certificate
SelfSignCa.CertificateSigning()
logging.info(f"Successful create self-signed certificate |{Address4} |{Address6}")
exit(0)
except Exception as RunTimeError:
logging.warning(f"Script error |{RunTimeError}")
exit(1)
# QC 2026C27