feat: Let's Encrypt integration, dual IP prompts, firewall checks, and CA utilities

- Add Let's Encrypt support in setup scripts with certbot auto-install (winget/pip/python -m fallbacks)
- Separate VM External IP and Host External IP prompts during setup
- Firewall rule creation only prompts when DuneDashboard rule doesn't exist
- HTTP redirect server tries 0.0.0.0:80 first, falls back to 127.0.0.1:80
- Cert monitor detects LE certs and runs certbot renew instead of local CA regeneration
- Add ssl_domain and ssl_email settings
- Add install-ca-cert.bat and clean-ca-certs.bat utilities for Windows CA management
- Update README with setup flow details, LE docs, and firewall notes
This commit is contained in:
Reditus committed 2026-05-12 09:07:51 +01:00
1 parent f22f3bdf8d
commit 846b27e834
12 files changed
+987 -79

No files matched your search

+6
View File
@@ -20,6 +20,8 @@ DEFAULTS = {
'secret_key': 'change-me-to-random-string',
'ssl_cert': None,
'ssl_key': None,
'ssl_domain': None,
'ssl_email': None,
},
'database': {
'host': '127.0.0.1',
@@ -57,6 +59,10 @@ DEFAULTS = {
'max_bytes': 10485760,
'backup_count': 5,
},
'ssl': {
'check_interval_hours': 24,
'renewal_days_before_expiry': 30,
},
}
+91 -1
View File
@@ -4,6 +4,7 @@ import os
import sys
import logging
import logging.handlers
import threading
from flask import Flask, request
from flask_socketio import SocketIO
from flask_talisman import Talisman
@@ -39,8 +40,16 @@ def create_app(settings_path=None):
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
ssl_enabled = bool(
settings['dashboard'].get('ssl_cert')
and settings['dashboard'].get('ssl_key')
and settings['dashboard']['ssl_cert'] != 'null'
and settings['dashboard']['ssl_key'] != 'null'
)
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
if not settings['dashboard']['debug']:
Talisman(app, content_security_policy=None, force_https=False)
Talisman(app, content_security_policy=None, force_https=ssl_enabled)
_setup_logging(settings)
@@ -114,6 +123,87 @@ def create_app(settings_path=None):
except Exception as e:
logging.warning(f"Could not auto-detect K8s namespace: {e}")
# Check SSL certificate expiry and start background monitor
if ssl_enabled:
try:
from app.utils.ssl import check_cert_expiry, generate_cert
cert_path = str(settings['dashboard']['ssl_cert']).strip("'\"")
key_path = str(settings['dashboard']['ssl_key']).strip("'\"")
is_expiring, days_remaining, msg = check_cert_expiry(cert_path)
if is_expiring:
logging.warning(f"SSL: {msg}")
else:
logging.info(f"SSL: {msg}")
def _cert_monitor():
"""Background thread that checks and regenerates expiring SSL certs."""
import time
check_interval = settings.get('ssl', {}).get('check_interval_hours', 24) * 3600
renewal_days = settings.get('ssl', {}).get('renewal_days_before_expiry', 30)
server_ip = settings['server'].get('host', '')
ssl_dir = os.path.dirname(cert_path)
ca_cert = os.path.join(ssl_dir, 'ca.pem')
ca_key = os.path.join(ssl_dir, 'ca-key.pem')
ca_available = os.path.exists(ca_cert) and os.path.exists(ca_key)
is_le = 'letsencrypt' in cert_path.lower() or 'certbot' in cert_path.lower()
le_domain = settings['dashboard'].get('ssl_domain')
def _restart_app():
import subprocess
if os.name == 'nt':
launcher = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'start.bat')
if os.path.exists(launcher):
subprocess.Popen(['cmd', '/c', 'start', '', launcher], shell=True)
else:
subprocess.Popen([sys.executable, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'run.py')], creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
launcher = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'start.sh')
if os.path.exists(launcher):
subprocess.Popen(['bash', launcher], start_new_session=True)
else:
subprocess.Popen([sys.executable, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'run.py')], start_new_session=True)
os._exit(0)
while True:
time.sleep(check_interval)
try:
is_expiring, days_left, _ = check_cert_expiry(cert_path, warning_days=renewal_days)
if is_expiring:
if is_le and le_domain:
logging.info(f"SSL: Let's Encrypt certificate expiring soon ({days_left} days). Running certbot renew...")
import subprocess
result = subprocess.run(['certbot', 'renew', '--quiet'], capture_output=True, timeout=300)
if result.returncode == 0:
logging.info("SSL: Let's Encrypt certificate renewed. Restarting to apply...")
_restart_app()
else:
logging.error(f"SSL: certbot renew failed: {result.stderr.decode()}")
elif ca_available:
logging.info(f"SSL: Certificate expiring soon ({days_left} days). Regenerating...")
san_ips = [server_ip, '127.0.0.1'] if server_ip else ['127.0.0.1']
generate_cert(
cert_path=cert_path,
key_path=key_path,
common_name=server_ip or 'localhost',
san_ips=san_ips,
san_dns=['localhost'],
ca_cert_path=ca_cert,
ca_key_path=ca_key,
)
logging.info("SSL: Certificate regenerated. Restarting to apply...")
_restart_app()
else:
logging.warning("SSL: Certificate expiring but no CA key available. Cannot regenerate.")
except Exception as e:
logging.error(f"SSL: Background cert check failed: {e}")
monitor_thread = threading.Thread(target=_cert_monitor, daemon=True)
monitor_thread.start()
logging.info("SSL: Background certificate monitor started")
except Exception as e:
logging.debug(f"Could not initialize SSL cert monitor: {e}")
app.dune_settings = settings
app.dune_services = services
+172 -13
View File
@@ -1,31 +1,36 @@
"""Generate self-signed SSL certificate for HTTPS"""
"""Generate self-signed SSL certificate for HTTPS with SAN extensions"""
import os
import datetime
import ipaddress
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
def generate_cert(cert_path, key_path):
"""Generate a self-signed certificate."""
# Generate private key
def generate_ca(ca_cert_path, ca_key_path, days_valid=3650):
"""Generate a self-signed CA certificate.
Args:
ca_cert_path: Path to write the CA certificate (PEM format).
ca_key_path: Path to write the CA private key (PEM format).
days_valid: CA certificate validity in days (default: 10 years).
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
key_size=4096,
)
# Generate subject/issuer
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Remote"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "Local"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dune Dashboard"),
x509.NameAttribute(NameOID.COMMON_NAME, "localhost"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dune Dashboard CA"),
x509.NameAttribute(NameOID.COMMON_NAME, "Dune Dashboard Local CA"),
])
# Build cert
cert = (
x509.CertificateBuilder()
.subject_name(subject)
@@ -33,15 +38,129 @@ def generate_cert(cert_path, key_path):
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=3650))
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=days_valid))
.add_extension(
x509.BasicConstraints(ca=True, path_length=None),
critical=True,
)
.add_extension(
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=True,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
critical=False,
)
.sign(key, hashes.SHA256())
)
# Write cert
with open(ca_cert_path, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
with open(ca_key_path, "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
print(f"CA certificate generated: {ca_cert_path}")
print(f"CA key generated: {ca_key_path}")
def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
common_name="localhost", san_ips=None, san_dns=None, days_valid=365):
"""Generate a server certificate, optionally signed by a CA.
Args:
cert_path: Path to write the server certificate (PEM format).
key_path: Path to write the server private key (PEM format).
ca_cert_path: Path to CA certificate. If None, self-signed.
ca_key_path: Path to CA private key. If None, self-signed.
common_name: CN for the certificate subject (default: localhost).
san_ips: List of IP addresses to include in SAN extension.
san_dns: List of DNS names to include in SAN extension.
days_valid: Certificate validity in days (default: 365).
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
subject = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Remote"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "Local"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dune Dashboard"),
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
])
# Build SAN entries
san_entries = [x509.DNSName(common_name)]
if san_ips:
for ip in san_ips:
try:
san_entries.append(x509.IPAddress(ipaddress.ip_address(ip)))
except ValueError:
pass
if san_dns:
for dns in san_dns:
san_entries.append(x509.DNSName(dns))
# Deduplicate SAN entries
san_entries = list(dict.fromkeys(san_entries))
builder = (
x509.CertificateBuilder()
.subject_name(subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=days_valid))
.add_extension(
x509.SubjectAlternativeName(san_entries),
critical=False,
)
)
if ca_cert_path and ca_key_path and os.path.exists(ca_cert_path) and os.path.exists(ca_key_path):
# Sign with CA
with open(ca_cert_path, "rb") as f:
ca_cert = x509.load_pem_x509_certificate(f.read())
with open(ca_key_path, "rb") as f:
ca_key = serialization.load_pem_private_key(f.read(), password=None)
builder = (
builder
.issuer_name(ca_cert.subject)
.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),
critical=False,
)
)
cert = builder.sign(ca_key, hashes.SHA256())
sign_type = "CA-signed"
else:
# Self-signed
builder = builder.issuer_name(subject)
cert = builder.sign(key, hashes.SHA256())
sign_type = "self-signed"
with open(cert_path, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
# Write key
with open(key_path, "wb") as f:
f.write(
key.private_bytes(
@@ -51,8 +170,48 @@ def generate_cert(cert_path, key_path):
)
)
print(f"SSL certificate generated: {cert_path}")
san_info = ", ".join(str(e) for e in san_entries)
print(f"SSL certificate generated ({sign_type}): {cert_path} (CN={common_name}, SAN=[{san_info}])")
print(f"SSL key generated: {key_path}")
print(f"Valid for {days_valid} days")
def check_cert_expiry(cert_path, warning_days=30):
"""Check if a certificate is expiring soon.
Args:
cert_path: Path to the certificate file.
warning_days: Days before expiry to trigger warning.
Returns:
Tuple of (is_expiring: bool, days_remaining: int or None, message: str).
"""
if not os.path.exists(cert_path):
return False, None, "Certificate file not found"
try:
with open(cert_path, "rb") as f:
cert = x509.load_pem_x509_certificate(f.read())
now = datetime.datetime.utcnow()
# not_valid_after_utc was added in cryptography 42.0.0
# Fall back to not_valid_after for older versions
expiry_attr = getattr(cert, 'not_valid_after_utc', None)
if expiry_attr is not None:
expiry = expiry_attr.replace(tzinfo=None)
else:
expiry = cert.not_valid_after
days_remaining = (expiry - now).days
if days_remaining <= 0:
return True, days_remaining, f"EXPIRED: Certificate expired {abs(days_remaining)} days ago"
elif days_remaining <= warning_days:
return True, days_remaining, f"WARNING: Certificate expires in {days_remaining} days"
else:
return False, days_remaining, f"OK: Certificate valid for {days_remaining} days"
except Exception as e:
return False, None, f"Error checking certificate: {e}"
if __name__ == "__main__":
base_dir = os.path.dirname(os.path.abspath(__file__))