mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-21 04:23:15 +01:00
Show served certificate status for App Gateway hosts
This commit is contained in:
@@ -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}
|
||||||
@@ -10,6 +10,7 @@ urlpatterns = [
|
|||||||
path('application/manage/', views.view_manage_application, name='manage_application'),
|
path('application/manage/', views.view_manage_application, name='manage_application'),
|
||||||
path('application/delete/', views.view_delete_application, name='delete_application'),
|
path('application/delete/', views.view_delete_application, name='delete_application'),
|
||||||
path('application/view/', views.view_application_details, name='view_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
|
# Application Hosts
|
||||||
path('host/manage/', views.view_manage_application_host, name='manage_application_host'),
|
path('host/manage/', views.view_manage_application_host, name='manage_application_host'),
|
||||||
|
|||||||
@@ -4,12 +4,16 @@ from django.conf import settings
|
|||||||
from django.contrib import messages
|
from django.contrib import messages
|
||||||
from django.contrib.auth.decorators import login_required
|
from django.contrib.auth.decorators import login_required
|
||||||
from django.db.models import F, ProtectedError
|
from django.db.models import F, ProtectedError
|
||||||
|
from django.http import JsonResponse
|
||||||
from django.shortcuts import render, get_object_or_404, redirect
|
from django.shortcuts import render, get_object_or_404, redirect
|
||||||
from django.urls import reverse
|
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.utils.translation import gettext as _
|
||||||
from django.views.decorators.http import require_POST
|
from django.views.decorators.http import require_POST
|
||||||
|
|
||||||
from app_gateway.caddy_config_export import export_caddy_config
|
from app_gateway.caddy_config_export import export_caddy_config
|
||||||
|
from app_gateway.certificate_status import inspect_certificate
|
||||||
from app_gateway.forms import (
|
from app_gateway.forms import (
|
||||||
ApplicationForm, ApplicationHostForm, AccessPolicyForm,
|
ApplicationForm, ApplicationHostForm, AccessPolicyForm,
|
||||||
ApplicationPolicyForm, ApplicationRouteForm, DnsChallengeCredentialForm
|
ApplicationPolicyForm, ApplicationRouteForm, DnsChallengeCredentialForm
|
||||||
@@ -66,11 +70,48 @@ def view_application_details(request):
|
|||||||
'hosts': hosts,
|
'hosts': hosts,
|
||||||
'routes': routes,
|
'routes': routes,
|
||||||
'is_reserved': is_reserved,
|
'is_reserved': is_reserved,
|
||||||
|
'caddy_enabled': settings.CADDY_ENABLED,
|
||||||
'page_title': _('Application Details'),
|
'page_title': _('Application Details'),
|
||||||
}
|
}
|
||||||
return render(request, 'app_gateway/application_details.html', context)
|
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
|
@login_required
|
||||||
def view_manage_application(request):
|
def view_manage_application(request):
|
||||||
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
|
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
|
||||||
|
|||||||
@@ -74,6 +74,7 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<th>{% trans 'Hostname' %}</th>
|
<th>{% trans 'Hostname' %}</th>
|
||||||
<th>{% trans 'Certificate' %}</th>
|
<th>{% trans 'Certificate' %}</th>
|
||||||
|
{% if caddy_enabled %}<th>{% trans 'Status' %}</th>{% endif %}
|
||||||
<th>{% trans 'Actions' %}</th>
|
<th>{% trans 'Actions' %}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -88,6 +89,11 @@
|
|||||||
<small class="text-muted">({% trans 'no fallback' %})</small>
|
<small class="text-muted">({% trans 'no fallback' %})</small>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
{% if caddy_enabled %}
|
||||||
|
<td class="certificate-status" data-host-uuid="{{ host.uuid }}">
|
||||||
|
<i class="fas fa-spinner fa-spin text-muted"></i>
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
<td style="width: 15%" class="text-nowrap">
|
<td style="width: 15%" class="text-nowrap">
|
||||||
{% if host.certificate_type != 'self_signed' %}
|
{% if host.certificate_type != 'self_signed' %}
|
||||||
<form method="post" action="{% url 'retry_application_host_certificate' %}?uuid={{ host.uuid }}" class="d-inline">
|
<form method="post" action="{% url 'retry_application_host_certificate' %}?uuid={{ host.uuid }}" class="d-inline">
|
||||||
@@ -180,3 +186,30 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block custom_page_scripts %}
|
||||||
|
{% if caddy_enabled and hosts %}
|
||||||
|
<script>
|
||||||
|
$(document).ready(function () {
|
||||||
|
$.getJSON("{% url 'application_certificate_status' %}?uuid={{ application.uuid }}", function (data) {
|
||||||
|
$('.certificate-status').each(function () {
|
||||||
|
var cell = $(this);
|
||||||
|
var hostStatus = data.hosts[cell.data('host-uuid')];
|
||||||
|
cell.empty();
|
||||||
|
if (!hostStatus) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cell.append(
|
||||||
|
$('<span class="badge"></span>')
|
||||||
|
.addClass('badge-' + hostStatus.css_class)
|
||||||
|
.attr('title', hostStatus.detail)
|
||||||
|
.text(hostStatus.label)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}).fail(function () {
|
||||||
|
$('.certificate-status').html('<span class="text-muted">-</span>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user