-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_certs.py
More file actions
73 lines (58 loc) · 2.36 KB
/
generate_certs.py
File metadata and controls
73 lines (58 loc) · 2.36 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
import os
import subprocess
import sys
# Define certificate directory
CERT_DIR = "/home/ubuntu/adguard/certs/"
# File paths
KEY_PATH = os.path.join(CERT_DIR, "adguard.key")
CSR_PATH = os.path.join(CERT_DIR, "adguard.csr")
CERT_PATH = os.path.join(CERT_DIR, "adguard.crt")
EXT_PATH = os.path.join(CERT_DIR, "adguard.ext")
CA_CERT_PATH = os.path.join(CERT_DIR, "myCA.pem")
CA_KEY_PATH = os.path.join(CERT_DIR, "myCA.key")
def generate_certificate(ip_address):
try:
# Generate server private key
subprocess.run(["openssl", "genrsa", "-out", KEY_PATH, "2048"], check=True)
# Create cert signing request (CSR) with the IP address as the common name
subprocess.run([
"openssl", "req", "-new", "-key", KEY_PATH, "-out", CSR_PATH,
"-subj", f"/CN={ip_address}/O=secretlab/L=Norman/ST=OK/C=US"
], check=True)
# Create the extension file for the certificate
with open(EXT_PATH, "w") as ext_file:
ext_file.write(f"""
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
IP.1 = {ip_address}
""")
# Sign the CSR to create the server certificate
subprocess.run([
"openssl", "x509", "-req", "-in", CSR_PATH, "-CA", CA_CERT_PATH, "-CAkey", CA_KEY_PATH,
"-CAcreateserial", "-out", CERT_PATH, "-days", "825", "-sha256", "-extfile", EXT_PATH
], check=True)
print(f"Certificate generated successfully for IP: {ip_address}")
except subprocess.CalledProcessError as e:
print(f"Error generating certificate: {e}")
def restart_adguardhome():
try:
# Restart AdGuardHome service
subprocess.run(["sudo", "systemctl", "restart", "adguardhome"], check=True)
print("AdGuardHome restarted successfully.")
except subprocess.CalledProcessError as e:
print(f"Error restarting AdGuardHome: {e}")
def main():
# Check if the IP address is provided as a command-line argument
if len(sys.argv) != 2:
print("Usage: python generate_certs.py <new_ip_address>")
sys.exit(1)
new_ip = sys.argv[1]
# Generate the new certificate
generate_certificate(new_ip)
# Restart AdGuardHome to apply the new certificates
restart_adguardhome()
if __name__ == "__main__":
main()