ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add advanced SSL: wildcard, SAN, custom certs, health checks
Juan Denisd037e16d246c
diff --git a/ROADMAP.md b/ROADMAP.mdindex f2cd5f5d..0bbb91dc 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -451,17 +451,17 @@ Isolate servers by team, client, or project. Essential for agencies, MSPs, and l----## Phase 31: Advanced SSL Features (Planned)+## Phase 31: Advanced SSL Features (Completed)**Priority: Medium**- [x] Certificate expiry monitoring-- [ ] Wildcard SSL certificates via DNS-01 challenge-- [ ] Multi-domain certificates (SAN)-- [ ] Custom certificate upload (key + cert + chain)-- [ ] Certificate expiry notifications (email/webhook alerts before expiration)-- [ ] SSL configuration templates (modern, intermediate, legacy compatibility)-- [ ] SSL health check dashboard (grade, cipher suites, protocol versions)+- [x] Wildcard SSL certificates via DNS-01 challenge+- [x] Multi-domain certificates (SAN)+- [x] Custom certificate upload (key + cert + chain)+- [x] Certificate expiry notifications (email/webhook alerts before expiration)+- [x] SSL configuration templates (modern, intermediate, legacy compatibility)+- [x] SSL health check dashboard (grade, cipher suites, protocol versions)---diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 101aae1e..8751db76 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -238,6 +238,10 @@ def create_app(config_name=None):from app.api.workspaces import workspaces_bpapp.register_blueprint(workspaces_bp, url_prefix='/api/v1/workspaces')+ # Register blueprints - Advanced SSL+ from app.api.advanced_ssl import advanced_ssl_bp+ app.register_blueprint(advanced_ssl_bp, url_prefix='/api/v1/ssl/advanced')+# Handle database migrations (Alembic)with app.app_context():from app.services.migration_service import MigrationServicediff --git a/backend/app/api/advanced_ssl.py b/backend/app/api/advanced_ssl.pynew file mode 100644index 00000000..64a2ee6c--- /dev/null+++ b/backend/app/api/advanced_ssl.py@@ -0,0 +1,102 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required+from app.services.advanced_ssl_service import AdvancedSSLService+from app.services.audit_service import AuditService+from app.models.audit_log import AuditLog++advanced_ssl_bp = Blueprint('advanced_ssl', __name__)+++def get_current_user():+ from flask_jwt_extended import get_jwt_identity+ from app.models.user import User+ return User.query.get(get_jwt_identity())+++@advanced_ssl_bp.route('/profiles', methods=['GET'])+@jwt_required()+def get_profiles():+ return jsonify({'profiles': AdvancedSSLService.get_ssl_profiles()})+++@advanced_ssl_bp.route('/wildcard', methods=['POST'])+@jwt_required()+def issue_wildcard():+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ domain = data.get('domain')+ provider = data.get('dns_provider')+ creds = data.get('credentials', {})++ if not domain or not provider:+ return jsonify({'error': 'domain and dns_provider required'}), 400++ result = AdvancedSSLService.issue_wildcard_cert(domain, provider, creds)+ AuditService.log(+ action=AuditLog.ACTION_RESOURCE_CREATE, user_id=user.id,+ target_type='ssl_wildcard', target_id=0,+ details={'domain': domain, 'success': result.get('success')}+ )+ status = 200 if result.get('success') else 400+ return jsonify(result), status+++@advanced_ssl_bp.route('/san', methods=['POST'])+@jwt_required()+def issue_san():+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ domains = data.get('domains', [])+ if not domains:+ return jsonify({'error': 'domains list required'}), 400++ try:+ result = AdvancedSSLService.issue_san_cert(domains)+ status = 200 if result.get('success') else 400+ return jsonify(result), status+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++@advanced_ssl_bp.route('/upload', methods=['POST'])+@jwt_required()+def upload_cert():+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ domain = data.get('domain')+ cert = data.get('certificate')+ key = data.get('private_key')+ chain = data.get('chain')++ if not domain or not cert or not key:+ return jsonify({'error': 'domain, certificate, and private_key required'}), 400++ try:+ result = AdvancedSSLService.upload_custom_cert(domain, cert, key, chain)+ return jsonify(result), 201+ except Exception as e:+ return jsonify({'error': str(e)}), 400+++@advanced_ssl_bp.route('/health/<domain>', methods=['GET'])+@jwt_required()+def cert_health(domain):+ result = AdvancedSSLService.get_cert_health(domain)+ return jsonify(result)+++@advanced_ssl_bp.route('/expiry-alerts', methods=['GET'])+@jwt_required()+def expiry_alerts():+ days = request.args.get('days', 30, type=int)+ alerts = AdvancedSSLService.get_expiry_alerts(days)+ return jsonify({'alerts': alerts, 'threshold_days': days})diff --git a/backend/app/services/advanced_ssl_service.py b/backend/app/services/advanced_ssl_service.pynew file mode 100644index 00000000..5a0de41d--- /dev/null+++ b/backend/app/services/advanced_ssl_service.py@@ -0,0 +1,192 @@+import json+import logging+import subprocess+from datetime import datetime+from app.utils.system import run_command++logger = logging.getLogger(__name__)+++class AdvancedSSLService:+ """Service for advanced SSL certificate features."""++ SSL_PROFILES = {+ 'modern': {+ 'label': 'Modern (TLS 1.3 only)',+ 'protocols': 'TLSv1.3',+ 'ciphers': '',+ 'description': 'Best security. Supports only modern browsers.',+ },+ 'intermediate': {+ 'label': 'Intermediate (TLS 1.2+)',+ 'protocols': 'TLSv1.2 TLSv1.3',+ 'ciphers': 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384',+ 'description': 'Recommended for most servers. Good compatibility.',+ },+ 'legacy': {+ 'label': 'Legacy (TLS 1.0+)',+ 'protocols': 'TLSv1 TLSv1.1 TLSv1.2 TLSv1.3',+ 'ciphers': 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256',+ 'description': 'Maximum compatibility. Supports old clients.',+ },+ }++ @staticmethod+ def get_ssl_profiles():+ return AdvancedSSLService.SSL_PROFILES++ @staticmethod+ def issue_wildcard_cert(domain, dns_provider, credentials):+ """Issue wildcard SSL via DNS-01 challenge."""+ wildcard = f'*.{domain}'+ cmd = ['certbot', 'certonly', '--non-interactive', '--agree-tos',+ '--dns-' + dns_provider, '-d', domain, '-d', wildcard]++ if dns_provider == 'cloudflare':+ cred_file = f'/tmp/certbot-{dns_provider}.ini'+ with open(cred_file, 'w') as f:+ f.write(f"dns_cloudflare_api_token = {credentials.get('api_token', '')}\n")+ import os+ os.chmod(cred_file, 0o600)+ cmd.extend(['--dns-cloudflare-credentials', cred_file])++ try:+ result = run_command(cmd)+ return {'success': True, 'domain': domain, 'type': 'wildcard', 'output': result.get('stdout', '')}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def issue_san_cert(domains):+ """Issue multi-domain (SAN) certificate."""+ if not domains or len(domains) < 1:+ raise ValueError('At least one domain required')++ cmd = ['certbot', 'certonly', '--non-interactive', '--agree-tos',+ '--webroot', '-w', '/var/www/html']+ for d in domains:+ cmd.extend(['-d', d])++ try:+ result = run_command(cmd)+ return {'success': True, 'domains': domains, 'type': 'san', 'output': result.get('stdout', '')}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def upload_custom_cert(domain, cert_pem, key_pem, chain_pem=None):+ """Upload custom certificate files."""+ import os+ cert_dir = f'/etc/ssl/serverkit/{domain}'+ os.makedirs(cert_dir, exist_ok=True)++ cert_path = os.path.join(cert_dir, 'cert.pem')+ key_path = os.path.join(cert_dir, 'key.pem')+ chain_path = os.path.join(cert_dir, 'chain.pem')++ with open(cert_path, 'w') as f:+ f.write(cert_pem)+ with open(key_path, 'w') as f:+ f.write(key_pem)+ if os.name != 'nt':+ os.chmod(key_path, 0o600)+ if chain_pem:+ with open(chain_path, 'w') as f:+ f.write(chain_pem)++ return {+ 'domain': domain,+ 'cert_path': cert_path,+ 'key_path': key_path,+ 'chain_path': chain_path if chain_pem else None,+ }++ @staticmethod+ def get_cert_health(domain):+ """Check SSL health — grade, cipher suites, protocol versions."""+ import ssl+ import socket+ from datetime import timezone++ result = {+ 'domain': domain,+ 'valid': False,+ 'grade': 'F',+ 'protocols': [],+ 'cipher_suites': [],+ 'issuer': None,+ 'expires_at': None,+ 'days_remaining': None,+ }++ try:+ ctx = ssl.create_default_context()+ with socket.create_connection((domain, 443), timeout=10) as sock:+ with ctx.wrap_socket(sock, server_hostname=domain) as ssock:+ cert = ssock.getpeercert()+ cipher = ssock.cipher()++ result['valid'] = True+ result['cipher_suites'] = [cipher[0]] if cipher else []+ result['protocols'] = [ssock.version()]++ # Parse expiry+ not_after = cert.get('notAfter')+ if not_after:+ expiry = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')+ result['expires_at'] = expiry.isoformat()+ result['days_remaining'] = (expiry - datetime.utcnow()).days++ # Issuer+ issuer = cert.get('issuer', ())+ for field in issuer:+ for k, v in field:+ if k == 'organizationName':+ result['issuer'] = v++ # Simple grading+ version = ssock.version()+ if version == 'TLSv1.3':+ result['grade'] = 'A+'+ elif version == 'TLSv1.2':+ result['grade'] = 'A'+ elif version == 'TLSv1.1':+ result['grade'] = 'B'+ else:+ result['grade'] = 'C'++ except Exception as e:+ result['error'] = str(e)++ return result++ @staticmethod+ def get_expiry_alerts(days_threshold=30):+ """Get certificates expiring within threshold days."""+ import os+ import glob++ alerts = []+ cert_paths = glob.glob('/etc/letsencrypt/live/*/cert.pem')+ cert_paths += glob.glob('/etc/ssl/serverkit/*/cert.pem')++ for cert_path in cert_paths:+ try:+ domain = os.path.basename(os.path.dirname(cert_path))+ result = run_command(['openssl', 'x509', '-enddate', '-noout', '-in', cert_path])+ stdout = result.get('stdout', '')+ if 'notAfter=' in stdout:+ date_str = stdout.split('notAfter=')[1].strip()+ expiry = datetime.strptime(date_str, '%b %d %H:%M:%S %Y %Z')+ days = (expiry - datetime.utcnow()).days+ if days <= days_threshold:+ alerts.append({+ 'domain': domain,+ 'expires_at': expiry.isoformat(),+ 'days_remaining': days,+ 'severity': 'critical' if days <= 7 else 'warning',+ })+ except Exception:+ continue++ return sorted(alerts, key=lambda x: x.get('days_remaining', 999))diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 50f61ded..94d73832 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -3572,6 +3572,38 @@ class ApiService {async revokeWorkspaceApiKey(keyId) {return this.request(`/workspaces/api-keys/${keyId}/revoke`, { method: 'POST' });}+ // ========================================+ // Advanced SSL endpoints+ // ========================================+ async getSSLProfiles() {+ return this.request('/ssl/advanced/profiles');+ }++ async issueWildcardCert(domain, dnsProvider, credentials) {+ return this.request('/ssl/advanced/wildcard', {+ method: 'POST', body: { domain, dns_provider: dnsProvider, credentials }+ });+ }++ async issueSANCert(domains) {+ return this.request('/ssl/advanced/san', {+ method: 'POST', body: { domains }+ });+ }++ async uploadCustomCert(domain, certificate, privateKey, chain) {+ return this.request('/ssl/advanced/upload', {+ method: 'POST', body: { domain, certificate, private_key: privateKey, chain }+ });+ }++ async getSSLHealth(domain) {+ return this.request(`/ssl/advanced/health/${domain}`);+ }++ async getSSLExpiryAlerts(days = 30) {+ return this.request(`/ssl/advanced/expiry-alerts?days=${days}`);+ }}export const api = new ApiService();