diff --git a/app_gateway/certificate_status.py b/app_gateway/certificate_status.py new file mode 100644 index 0000000..ceb4abc --- /dev/null +++ b/app_gateway/certificate_status.py @@ -0,0 +1,78 @@ +import socket +import ssl +import subprocess +from datetime import datetime, timezone + +# Caddy shares the network namespace of the WireGuard WebAdmin container +CADDY_TLS_ADDRESS = ('127.0.0.1', 443) +CONNECTION_TIMEOUT = 3 +INTERNAL_CA_NAME = 'Caddy Local Authority' + + +def _parse_not_after(value): + return datetime.strptime(value, '%b %d %H:%M:%S %Y %Z').replace(tzinfo=timezone.utc) + + +def _issuer_name(issuer_fields): + issuer = dict(field[0] for field in issuer_fields) + return issuer.get('organizationName') or issuer.get('commonName') or '' + + +def _fetch_certificate(hostname, verify): + if verify: + context = ssl.create_default_context() + else: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + + with socket.create_connection(CADDY_TLS_ADDRESS, timeout=CONNECTION_TIMEOUT) as raw_socket: + with context.wrap_socket(raw_socket, server_hostname=hostname) as tls_socket: + if verify: + return tls_socket.getpeercert() + return tls_socket.getpeercert(binary_form=True) + + +def _describe_untrusted_certificate(certificate_der): + result = subprocess.run( + ['openssl', 'x509', '-inform', 'DER', '-noout', '-issuer', '-enddate', '-nameopt', 'RFC2253'], + input=certificate_der, capture_output=True, timeout=CONNECTION_TIMEOUT, + ) + issuer = '' + not_after = None + for line in result.stdout.decode(errors='replace').splitlines(): + if line.startswith('issuer='): + issuer_parts = dict( + part.split('=', 1) for part in line[len('issuer='):].split(',') if '=' in part + ) + issuer = issuer_parts.get('O') or issuer_parts.get('CN') or '' + if INTERNAL_CA_NAME in line: + issuer = INTERNAL_CA_NAME + elif line.startswith('notAfter='): + not_after = _parse_not_after(line[len('notAfter='):]) + return issuer, not_after + + +def inspect_certificate(hostname): + """ + Return the status of the certificate Caddy serves for a hostname: + 'trusted', 'untrusted' (served but not trusted, e.g. internal CA) or 'unavailable'. + """ + try: + certificate = _fetch_certificate(hostname, verify=True) + return { + 'status': 'trusted', + 'issuer': _issuer_name(certificate.get('issuer', ())), + 'not_after': _parse_not_after(certificate['notAfter']), + } + except ssl.SSLCertVerificationError: + pass + except (OSError, ValueError): + return {'status': 'unavailable', 'issuer': '', 'not_after': None} + + try: + certificate_der = _fetch_certificate(hostname, verify=False) + issuer, not_after = _describe_untrusted_certificate(certificate_der) + except (OSError, ValueError, subprocess.SubprocessError): + return {'status': 'unavailable', 'issuer': '', 'not_after': None} + return {'status': 'untrusted', 'issuer': issuer, 'not_after': not_after} diff --git a/app_gateway/urls.py b/app_gateway/urls.py index ab1e48a..e694cb6 100644 --- a/app_gateway/urls.py +++ b/app_gateway/urls.py @@ -10,6 +10,7 @@ urlpatterns = [ path('application/manage/', views.view_manage_application, name='manage_application'), path('application/delete/', views.view_delete_application, name='delete_application'), path('application/view/', views.view_application_details, name='view_application'), + path('application/certificate_status/', views.view_application_certificate_status, name='application_certificate_status'), # Application Hosts path('host/manage/', views.view_manage_application_host, name='manage_application_host'), diff --git a/app_gateway/views.py b/app_gateway/views.py index d0d123a..bfcfd80 100644 --- a/app_gateway/views.py +++ b/app_gateway/views.py @@ -4,12 +4,16 @@ from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import F, ProtectedError +from django.http import JsonResponse from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse +from django.utils.formats import date_format +from django.utils.timezone import localtime from django.utils.translation import gettext as _ from django.views.decorators.http import require_POST from app_gateway.caddy_config_export import export_caddy_config +from app_gateway.certificate_status import inspect_certificate from app_gateway.forms import ( ApplicationForm, ApplicationHostForm, AccessPolicyForm, ApplicationPolicyForm, ApplicationRouteForm, DnsChallengeCredentialForm @@ -66,11 +70,48 @@ def view_application_details(request): 'hosts': hosts, 'routes': routes, 'is_reserved': is_reserved, + 'caddy_enabled': settings.CADDY_ENABLED, 'page_title': _('Application Details'), } return render(request, 'app_gateway/application_details.html', context) +@login_required +def view_application_certificate_status(request): + if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=20).exists(): + return JsonResponse({'error': _('Access Denied')}, status=403) + + application = get_object_or_404(Application, uuid=request.GET.get('uuid')) + if not settings.CADDY_ENABLED: + return JsonResponse({'caddy_enabled': False, 'hosts': {}}) + + hosts_status = {} + for application_host in application.hosts.all(): + certificate = inspect_certificate(application_host.hostname) + expiration = '' + if certificate['not_after']: + expiration = _('expires %(date)s') % { + 'date': date_format(localtime(certificate['not_after']), 'SHORT_DATETIME_FORMAT') + } + + if certificate['status'] == 'trusted': + css_class, label = 'success', _('Trusted') + detail = f"{certificate['issuer']}, {expiration}" + elif certificate['status'] == 'untrusted' and application_host.certificate_type == 'self_signed': + css_class, label = 'secondary', _('Self-signed') + detail = expiration + elif certificate['status'] == 'untrusted': + css_class, label = 'warning', _('Using fallback') + detail = _('The trusted certificate could not be issued yet, %(expiration)s') % {'expiration': expiration} + else: + css_class, label = 'danger', _('Unavailable') + detail = _('No certificate is being served for this hostname.') + + hosts_status[str(application_host.uuid)] = {'css_class': css_class, 'label': label, 'detail': detail} + + return JsonResponse({'caddy_enabled': True, 'hosts': hosts_status}) + + @login_required def view_manage_application(request): if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists(): diff --git a/templates/app_gateway/application_details.html b/templates/app_gateway/application_details.html index 210aaca..e78c432 100644 --- a/templates/app_gateway/application_details.html +++ b/templates/app_gateway/application_details.html @@ -74,6 +74,7 @@