Prepare Coulobre 0.12 role workspaces and hosting workflows #166

Merged
parkel merged 9 commits from release/0.12 into main 2026-11-23 23:57:31 +01:00
15 changed files with 1056 additions and 22 deletions
Showing only changes of commit 0263aa4bfa - Show all commits

No files matched your search

@@ -0,0 +1,97 @@
import json
from base64 import urlsafe_b64encode
from hashlib import sha256
from cryptography.fernet import Fernet, InvalidToken, MultiFernet
from django import forms
from django.conf import settings
from django.views.decorators.debug import sensitive_variables
from coulobre.web_certificates import (
MAX_CERTIFICATE_BYTES,
MAX_KEY_BYTES,
validated_pem,
)
UPLOAD_LIFETIME = 60 * 60
class CertificateUploadForm(forms.Form):
chain = forms.FileField(
label="Certificate chain (PEM)",
help_text="Include the website certificate followed by intermediates.",
)
key = forms.FileField(
label="Private key (PEM)",
help_text="Use its matching unencrypted private key.",
)
@sensitive_variables()
def clean(self):
data = super().clean()
if self.errors:
return data
try:
chain, key = (
read_upload(data[name], limit)
for name, limit in (
("chain", MAX_CERTIFICATE_BYTES),
("key", MAX_KEY_BYTES),
)
)
data["chain_pem"], data["key_pem"] = validated_pem(chain, key)
except (UnicodeError, ValueError) as error:
raise forms.ValidationError(
"Provide a valid PEM certificate chain and matching key."
) from error
return data
def read_upload(upload, limit):
data = upload.read(limit + 1)
if len(data) > limit:
raise ValueError("The uploaded file exceeds the size limit.")
return data.decode("ascii")
def upload_encryption():
return MultiFernet(
[
Fernet(
urlsafe_b64encode(
sha256(
b"coulobre-website-certificate\0"
+ secret.encode("utf-8")
).digest()
)
)
for secret in (settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS)
]
)
@sensitive_variables()
def seal_upload(site, customer_id, form):
response = json.dumps(
[
site.manifest(),
customer_id,
form.cleaned_data["chain_pem"],
form.cleaned_data["key_pem"],
]
).encode("utf-8")
return upload_encryption().encrypt(response).decode("ascii")
@sensitive_variables()
def open_upload(job):
try:
payload = upload_encryption().decrypt(
job.encrypted_upload.encode("ascii"), ttl=UPLOAD_LIFETIME
)
site, customer_id, chain, key = json.loads(payload)
if site == job.site and customer_id == job.requested_customer_id:
return chain, key
except (InvalidToken, UnicodeError, ValueError):
pass
raise ValueError("The certificate upload expired. Upload the files again.")
+202
View File
@@ -0,0 +1,202 @@
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import sensitive_variables
from django.views.decorators.http import require_http_methods, require_safe
from coulobre.domain_names import canonical_domain
from coulobre.web_certificates import ACTIONS
from coulobre.web_node import WebSite
from .access import customer_for_user
from .certificate_uploads import CertificateUploadForm, seal_upload
from .independent_websites import active_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteCertificateJob
from .resource_requests import lock_hosting_account, require_active_services
from .sftp import site_is_active
def account_certificate_sites(account):
sites = [
website.spec
for website in active_websites(account).filter(suspended=False)
]
if site_is_active(account):
sites.insert(0, WebSite(account.pk, account.primary_domain))
return {site.domain: site for site in sites}
@transaction.atomic
def queue_certificate(
account, site, actor, action, customer_id, *, encrypted_upload=""
):
account = lock_hosting_account(account.pk, customer_id)
require_active_services(account)
if account_certificate_sites(account).get(site.domain) != site:
raise ValidationError("This website is no longer active.")
recent = account.certificate_jobs.filter(site=site.manifest())
if recent.filter(finished_at__isnull=True).exists():
raise ValidationError("Wait for the current certificate operation.")
if (
action == "reissue"
and recent.filter(
action=action,
requested_at__gte=timezone.now() - timedelta(hours=12),
).exists()
):
raise ValidationError(
"Wait 12 hours before requesting another reissue."
)
WebsiteCertificateJob.objects.create(
account=account,
site=site.manifest(),
actor=actor,
requested_customer_id=customer_id,
action=action,
encrypted_upload=encrypted_upload,
)
@never_cache
@sensitive_variables("encrypted_upload", "upload_form")
@require_http_methods(("GET", "HEAD", "POST"))
def customer_certificates(request, pk):
customer = customer_for_user(request.user)
if customer is None:
raise PermissionDenied
account = get_object_or_404(
HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
)
sites = account_certificate_sites(account)
try:
domain = canonical_domain(
request.GET.get(
"domain", next(iter(sites), account.primary_domain)
)
)
except ValueError as error:
raise Http404 from error
site = sites.get(domain)
if "domain" in request.GET and site is None:
raise Http404
tab = request.GET.get("tab", "manage")
if tab not in {"manage", "acme", "history"}:
raise Http404
enabled = panel_feature_allowed("LOCAL_WEB_HTTPS")
problem = ""
is_upload = (
request.method == "POST" and request.POST.get("action") == "upload"
)
upload_form = CertificateUploadForm(
request.POST if is_upload else None,
request.FILES if is_upload else None,
)
if request.method == "POST" and (not is_upload or upload_form.is_valid()):
if not site or not enabled:
raise Http404
action = request.POST.get("action")
if action not in ACTIONS:
raise Http404
try:
encrypted_upload = (
seal_upload(site, customer.pk, upload_form)
if is_upload
else ""
)
queue_certificate(
account,
site,
request.user,
action,
customer.pk,
encrypted_upload=encrypted_upload,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
problem = " ".join(error.messages)
else:
return redirect(
reverse(
"panel:customer_certificates",
args=[account.pk],
query={"domain": domain, "tab": "history"},
)
)
history = []
certificate = None
if site:
jobs = account.certificate_jobs.filter(
site=site.manifest(),
requested_customer_id=customer.pk,
)
history = list(jobs.order_by("-pk")[:25])
certificate = jobs.exclude(certificate={}).order_by("-pk").first()
return render(
request,
"hosting/customer_certificates.html",
{
"account": account,
"sites": sites,
"domain": domain,
"tab": tab,
"certificate": certificate,
"upload_form": upload_form,
"history": history,
"enabled": enabled,
"problem": problem,
"site": site,
},
)
@never_cache
@require_safe
def operator_certificates(request):
if not (request.user.is_superuser and request.user.is_verified()):
raise PermissionDenied
mode = request.GET.get("tab", "websites")
if mode not in {"websites", "server"}:
raise Http404
accounts = HostingAccount.objects.filter(retired_at__isnull=True).order_by(
"primary_domain"
)
page_obj = Paginator(accounts, 30).get_page(request.GET.get("page"))
sites = (
[
(
site.domain,
account,
account.certificate_jobs.filter(site=site.manifest())
.exclude(certificate={})
.order_by("-pk")
.first(),
)
for account in page_obj
for site in account_certificate_sites(account).values()
]
if mode == "websites"
else []
)
return render(
request,
"hosting/operator_certificates.html",
{
"mode": mode,
"sites": sites,
"page_obj": page_obj,
"is_paginated": page_obj.has_other_pages,
"panel_origin": settings.PASSWORD_RESET_ORIGIN,
"imap_host": settings.MAIL_IMAP_HOST,
"submission_host": settings.MAIL_SUBMISSION_HOST,
},
)
@@ -0,0 +1,67 @@
# Generated by Django 5.2.19 on 2026-11-23 21:38
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0067_mail_delivery_search"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="WebsiteCertificateJob",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("site", models.JSONField()),
("action", models.CharField(max_length=12)),
(
"requested_customer_id",
models.PositiveBigIntegerField(null=True),
),
("certificate", models.JSONField(default=dict)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="certificate_jobs",
to="hosting.hostingaccount",
),
),
(
"actor",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.2.19 on 2026-11-23 21:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0068_website_certificate_jobs"),
]
operations = [
migrations.AddField(
model_name="websitecertificatejob",
name="encrypted_upload",
field=models.TextField(blank=True, default=""),
),
]
+18
View File
@@ -1019,6 +1019,24 @@ class WebHTTPS(ProvisioningJob):
verbose_name = "website HTTPS request"
class WebsiteCertificateJob(ProvisioningJob):
account = models.ForeignKey(
HostingAccount,
on_delete=models.CASCADE,
related_name="certificate_jobs",
)
site = models.JSONField()
action = models.CharField(max_length=12)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
)
requested_customer_id = models.PositiveBigIntegerField(null=True)
encrypted_upload = models.TextField(blank=True, default="")
certificate = models.JSONField(default=dict)
class WebsiteAlias(ProvisioningJob):
wait_for_website = models.BooleanField(default=False)
+70
View File
@@ -64,6 +64,7 @@ from .models import (
WebHTTPS,
WebProvisioningPlan,
WebsiteAlias,
WebsiteCertificateJob,
WebsiteRestoreJob,
WebsiteScheduledJob,
)
@@ -221,7 +222,15 @@ def dispatch_site_storage_limits():
@shared_task
def dispatch_web_https():
from .certificate_uploads import UPLOAD_LIFETIME
WebsiteCertificateJob.objects.filter(
requested_at__lte=timezone.now() - timedelta(seconds=UPLOAD_LIFETIME)
).exclude(encrypted_upload="").update(encrypted_upload="")
if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(
WebsiteCertificateJob, apply_certificate_job, WEB_HTTPS_QUEUE
)
dispatch_provisioning_jobs(
IndependentWebsite,
provision_independent_website,
@@ -1392,3 +1401,64 @@ def search_mail_delivery(job_id):
apply,
"The mail node did not return a delivery report.",
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def apply_certificate_job(job_id):
from django.views.decorators.debug import sensitive_variables
from coulobre.web_certificates import WebCertificateRequest
from .certificate_uploads import open_upload
from .certificate_views import account_certificate_sites
from .node_client import apply_on_local_node
@sensitive_variables()
def apply(job):
site = WebSite.from_manifest(job.site)
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"This hosting account is no longer available."
) from None
if (
account.services_suspended
or account.retired_at is not None
or account_certificate_sites(account).get(site.domain) != site
):
raise ValueError("This website is no longer active.")
spec = WebCertificateRequest(
site,
job.action,
*(open_upload(job) if job.action == "upload" else ()),
)
reply = apply_on_local_node(
spec,
"/run/coulobre-https-apply.sock",
"web node",
"certificate operation",
identity=spec.identity(),
)
certificate = reply.get("certificate")
if (
not isinstance(certificate, dict)
or type(certificate.get("installed")) is not bool
):
raise ValueError("The web node did not return certificate status.")
return {"certificate": certificate}
if settings.LOCAL_WEB_HTTPS:
run_provisioning_job(
WebsiteCertificateJob.objects.all(),
job_id,
apply,
"The HTTPS worker did not confirm the certificate operation.",
)
WebsiteCertificateJob.objects.filter(
pk=job_id, finished_at__isnull=False
).exclude(encrypted_upload="").update(encrypted_upload="")
@@ -0,0 +1,63 @@
{% extends "hosting/base.html" %}
{% block title %}SSL Certificates · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><div><h1>SSL Certificates</h1><p class="heading-meta">{{ account.primary_domain }}</p></div></header>
{% if sites %}
<section class="surface">
<form method="get" class="toolbar form-actions">
<label for="certificate-domain">Website</label>
<select id="certificate-domain" name="domain">{% for choice in sites %}<option value="{{ choice }}"{% if choice == domain %} selected{% endif %}>{{ choice }}</option>{% endfor %}</select>
<input type="hidden" name="tab" value="{{ tab }}">
<button type="submit" class="button secondary">Select website</button>
</form>
</section>
<nav class="account-navigation" aria-label="Certificates">
<a href="?domain={{ domain }}&amp;tab=manage"{% if tab == 'manage' %} aria-current="page"{% endif %}>Manage certificates</a>
<a href="?domain={{ domain }}&amp;tab=acme"{% if tab == 'acme' %} aria-current="page"{% endif %}>ACME settings</a>
<a href="?domain={{ domain }}&amp;tab=history"{% if tab == 'history' %} aria-current="page"{% endif %}>Provisioning history</a>
</nav>
{% if problem %}<p class="notice" role="alert">{{ problem }}</p>{% endif %}
{% if tab == 'manage' %}
<section class="surface editor-surface">
<h2>Last observed certificate</h2>
{% if certificate.certificate.installed %}
<dl>
<dt>Issuer</dt><dd>{{ certificate.certificate.issuer }}</dd>
<dt>Names</dt><dd>{{ certificate.certificate.names|join:", " }}</dd>
<dt>Expires</dt><dd>{{ certificate.certificate.not_after }}</dd>
<dt>Checked</dt><dd>{{ certificate.finished_at|date:"j M Y H:i" }} UTC</dd>
</dl>
{% elif certificate %}<p>No HTTPS certificate was installed when last checked.</p>
{% else %}<p>Check the website to see its current certificate.</p>{% endif %}
{% if enabled %}
<form class="form-actions" method="post">
{% csrf_token %}
<button type="submit" class="button secondary" name="action" value="inspect">Check certificate</button>
{% if certificate.certificate.source == "acme" %}<button type="submit" class="button secondary" name="action" value="reissue">Request reissue</button>
{% elif not certificate.certificate.installed %}<button type="submit" class="button primary" name="action" value="issue">Request certificate</button>{% endif %}
</form>
{% endif %}
</section>
{% if enabled %}
<details class="surface editor-surface"{% if upload_form.errors %} open{% endif %}>
<summary>Upload certificate</summary>
<form method="post" class="editor" enctype="multipart/form-data">{% csrf_token %}{{ upload_form.as_div }}
<button class="button secondary" type="submit" name="action" value="upload">Install uploaded certificate</button>
</form>
</details>
{% endif %}
{% elif tab == 'acme' %}
<section class="surface editor-surface" aria-label="ACME settings">
<dl><dt>Challenge method</dt><dd>HTTP-01</dd><dt>Renewal</dt><dd>Managed by Certbot on the web node</dd></dl>
<p>The website's DNS must resolve to this node and HTTP port 80 must be reachable for validation.</p>
<p>Wildcard certificates require DNS-01 support on the server.</p>
</section>
{% else %}
<section class="surface">
<ul class="workspace-list">{% for job in history %}
<li>{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.action|capfirst }} · {{ job.state|capfirst }}{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}</li>
{% empty %}<li>No certificate operations yet.</li>{% endfor %}</ul>
</section>
{% endif %}
{% else %}<p class="notice">Activate a website to manage its certificate.</p>{% endif %}
{% endblock %}
@@ -0,0 +1,27 @@
{% extends "hosting/base.html" %}
{% block title %}SSL Overview · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>SSL Overview</h1></header>
<nav class="account-navigation" aria-label="TLS overview">
<a href="?tab=websites"{% if mode == 'websites' %} aria-current="page"{% endif %}>Hosted websites</a>
<a href="?tab=server"{% if mode == 'server' %} aria-current="page"{% endif %}>Server SSL</a>
</nav>
{% if mode == 'server' %}
<section class="surface editor-surface">
<h2>Configured endpoints</h2>
<dl><dt>Panel origin</dt><dd>{{ panel_origin|default:"Unavailable" }}</dd>
<dt>IMAP</dt><dd>{{ imap_host|default:"Unavailable" }}</dd>
<dt>SMTP submission</dt><dd>{{ submission_host|default:"Unavailable" }}</dd>
</dl>
<a href="{% url 'panel:service_health' %}">Service health</a>
</section>
{% else %}
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">Website</th><th scope="col">Account</th><th scope="col">Last known issuer</th><th scope="col">Expiry</th></tr></thead>
<tbody>{% for domain, account, job in sites %}<tr>
<th scope="row">{{ domain }}</th><td><a href="{{ account.get_absolute_url }}">{{ account.name }}</a></td>
<td>{{ job.certificate.issuer|default:"Unavailable" }}</td><td>{{ job.certificate.not_after|default:"Unavailable" }}</td>
</tr>{% empty %}<tr><td colspan="4">No active websites on this page.</td></tr>{% endfor %}</tbody>
</table></div>{% include "hosting/pagination.html" %}</section>
{% endif %}
{% endblock %}
@@ -0,0 +1,96 @@
from datetime import UTC, datetime, timedelta
from unittest.mock import patch
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.x509.oid import NameOID
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from .models import (
Customer,
HostingAccount,
WebActivation,
WebProvisioningPlan,
WebsiteCertificateJob,
)
from .tasks import apply_certificate_job
def certificate_files(domain):
key = Ed25519PrivateKey.generate()
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, domain)])
now = datetime.now(UTC)
certificate = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(days=1))
.not_valid_after(now + timedelta(days=60))
.add_extension(
x509.SubjectAlternativeName([x509.DNSName(domain)]),
critical=False,
)
.sign(key, None)
)
return (
certificate.public_bytes(serialization.Encoding.PEM),
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
),
)
@override_settings(LOCAL_WEB_HTTPS=True)
class CertificateWorkspaceTests(TestCase):
def test_upload_is_scoped_encrypted_and_erased_after_worker_use(self):
users = get_user_model().objects
customer = Customer.objects.create(user=users.create_user("customer"))
outsider = Customer.objects.create(user=users.create_user("outsider"))
account = HostingAccount.objects.create(
name="Shop", primary_domain="shop.example.test", customer=customer
)
plan = WebProvisioningPlan.objects.create(
account=account,
primary_domain=account.primary_domain,
apache_config="Installed",
completed_at=timezone.now(),
)
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
url = reverse("panel:customer_certificates", args=[account.pk])
self.client.force_login(outsider.user)
self.assertEqual(self.client.get(url).status_code, 404)
self.client.force_login(customer.user)
self.assertContains(self.client.get(url), "Upload certificate")
chain, key = certificate_files(account.primary_domain)
upload = self.client.post(
url,
{
"action": "upload",
"chain": SimpleUploadedFile("chain.pem", chain),
"key": SimpleUploadedFile("key.pem", key),
},
)
self.assertEqual(upload.status_code, 302)
job = WebsiteCertificateJob.objects.get()
self.assertTrue(job.encrypted_upload)
self.assertNotIn("PRIVATE KEY", job.encrypted_upload)
with patch(
"coulobre.hosting.node_client.apply_on_local_node",
return_value={"certificate": {"installed": True}},
) as apply:
apply_certificate_job(job.pk)
job.refresh_from_db()
self.assertEqual(job.state, "configured")
self.assertEqual(job.encrypted_upload, "")
spec = apply.call_args.args[0]
self.assertEqual(spec.key.encode("ascii"), key)
self.assertNotIn("key", apply.call_args.kwargs["identity"])
@@ -1,4 +1,3 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase, override_settings
+7
View File
@@ -20,6 +20,7 @@ from .account_security import (
VerifyEmailView,
)
from .backup_restores import RestoreKind
from .certificate_views import customer_certificates, operator_certificates
from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .customer_backup_views import CustomerBackupView, CustomerRestoreView
from .dns_defaults_views import DnsDefaultsView
@@ -86,6 +87,12 @@ from .workspaces import customer_workspace, system_workspace
app_name = "panel"
urlpatterns = [
path("ssl/", operator_certificates, name="operator_certificates"),
path(
"hosting/<int:pk>/certificates/",
customer_certificates,
name="customer_certificates",
),
path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"),
path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"),
path(
+9 -1
View File
@@ -21,6 +21,7 @@ CUSTOMER_PAGES = {
"dns": ("DNS Editor", "account", "domains-dns"),
"php": ("PHP Settings", "account", "websites"),
"files": ("File Manager", "website_files", ""),
"certificates": ("SSL Certificates", "customer_certificates", ""),
"sftp": ("SFTP Users", "sftp_keys", ""),
"databases": ("Databases", "account", "databases"),
"email": ("Email Accounts", "account", "email"),
@@ -207,7 +208,13 @@ def groups_for(request, *, customer, manager):
[
link("accounts", "My hosting"),
*hosted(
"domains", "dns", "sftp", "databases", "php", "files"
"domains",
"dns",
"certificates",
"sftp",
"databases",
"php",
"files",
),
],
),
@@ -284,6 +291,7 @@ def groups_for(request, *, customer, manager):
link("theme_management", "Themes"),
link("announcements", "Message"),
link("directadmin_guide", "Import"),
link("operator_certificates", "SSL Overview"),
)
)
if user.is_superuser:
+298
View File
@@ -0,0 +1,298 @@
import fcntl
import os
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
from cryptography import x509
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives import serialization
from .node_files import (
check_root_file,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .web_node import WebSite
from .web_node_apply import (
SitePaths,
check_configuration,
check_site_link,
enable_apache_site,
locked_web_node,
run,
)
from .web_node_tls import (
certificate_lineage,
check_https_prerequisites,
custom_lineage,
https_paths,
install_https_configuration,
provision_https,
render_https_configuration,
request_certificate,
resolved_certificate_files,
validate_certificate_files,
)
ACTIONS = ("inspect", "issue", "reissue", "upload")
MAX_CERTIFICATE_BYTES = 32768
MAX_KEY_BYTES = 8192
CERTIFICATE_REQUEST_LIMIT = 65536
@dataclass(frozen=True)
class WebCertificateRequest:
site: WebSite
action: str
chain: str = field(default="", repr=False)
key: str = field(default="", repr=False)
def __post_init__(self):
if self.action not in ACTIONS:
raise ValueError("Choose a supported certificate operation.")
if self.action == "upload":
check_pem_size(self.chain, MAX_CERTIFICATE_BYTES)
check_pem_size(self.key, MAX_KEY_BYTES)
elif self.chain or self.key:
raise ValueError("This operation does not accept uploaded files.")
def identity(self):
return {
"operation": "manage_certificate",
"site": self.site.manifest(),
"action": self.action,
}
def manifest(self):
return self.identity() | (
{"chain": self.chain, "key": self.key}
if self.action == "upload"
else {}
)
@classmethod
def from_manifest(cls, data):
fields = {"operation", "site", "action"}
if data.get("action") == "upload":
fields |= {"chain", "key"}
if data.keys() != fields:
raise ValueError("Expected a certificate operation.")
return cls(
WebSite.from_manifest(data["site"]),
data["action"],
data.get("chain", ""),
data.get("key", ""),
)
def check_pem_size(value, limit):
if (
not isinstance(value, str)
or not value.isascii()
or not 1 <= len(value) <= limit
):
raise ValueError("Upload a supported PEM file within the size limit.")
def validated_pem(chain, key):
check_pem_size(chain, MAX_CERTIFICATE_BYTES)
check_pem_size(key, MAX_KEY_BYTES)
try:
chain_data = x509.load_pem_x509_certificates(chain.encode("ascii"))
private = serialization.load_pem_private_key(
key.encode("ascii"), password=None
)
public_format = serialization.PublicFormat.SubjectPublicKeyInfo
encoding = serialization.Encoding.PEM
if (
not chain_data
or len(chain_data) > 16
or chain_data[0].public_key().public_bytes(encoding, public_format)
!= private.public_key().public_bytes(encoding, public_format)
):
raise ValueError("The certificate and private key must match.")
return (
"".join(
cert.public_bytes(encoding).decode("ascii")
for cert in chain_data
),
private.private_bytes(
encoding,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
).decode("ascii"),
)
except (TypeError, ValueError, UnsupportedAlgorithm, AttributeError):
raise ValueError(
"Provide a valid certificate chain and matching "
"unencrypted private key."
) from None
def certificate_details(site):
paths = SitePaths.for_site(site)
config, enabled = https_paths(paths)
for directory in (config.parent, enabled.parent):
require_root_directory(directory)
if not config.exists() or not os.path.lexists(enabled):
return {"installed": False}
check_site_link(enabled, Path("../sites-available") / config.name)
check_configuration(
config,
render_https_configuration(site, socket_path=paths.apache_socket),
)
path, _ = resolved_certificate_files(site)
check_root_file(path)
with path.open("rb") as source:
data = source.read(65537)
if len(data) > 65536:
raise ValueError("The website certificate is too large.")
try:
certificate = x509.load_pem_x509_certificate(data)
names = certificate.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value.get_values_for_type(x509.DNSName)
except (ValueError, x509.ExtensionNotFound) as error:
raise ValueError(
"The website certificate could not be read."
) from error
return {
"installed": True,
"source": "uploaded"
if certificate_lineage(site).name == "active"
else "acme",
"issuer": certificate.issuer.rfc4514_string()[:350],
"names": [name[:253] for name in names[:60]],
"not_after": certificate.not_valid_after_utc.isoformat(),
}
def apply_website_certificate(request):
if os.geteuid() != 0:
raise ValueError("Run certificate management as root on the web node.")
site = request.site
if request.action == "issue":
provision_https(site)
elif request.action == "reissue":
reissue_certificate(site)
elif request.action == "upload":
install_uploaded_certificate(
site, *validated_pem(request.chain, request.key)
)
with locked_web_node(fcntl.LOCK_SH):
check_https_prerequisites(site, SitePaths.for_site(site))
return {"certificate": certificate_details(site)}
def replace_symlink(path, target):
with TemporaryDirectory(dir=path.parent) as directory:
staged = Path(directory) / "link"
staged.symlink_to(target)
staged.replace(path)
def reload_apache():
run("/usr/sbin/apache2ctl", "configtest")
run("/usr/sbin/service", "apache2", "reload")
def reissue_certificate(site):
with locked_web_node(fcntl.LOCK_EX):
paths = SitePaths.for_site(site)
check_https_prerequisites(site, paths)
lineage = certificate_lineage(site)
if lineage.name == "active":
raise ValueError("This website uses an uploaded certificate.")
previous = {}
if lineage.exists():
resolved_certificate_files(site)
previous = {
path: path.readlink()
for name in ("fullchain", "privkey", "cert", "chain")
if (path := lineage / f"{name}.pem").is_symlink()
}
try:
request_certificate(site, force=True)
apache, enabled = https_paths(paths)
install_https_configuration(
site, apache, enabled, socket_path=paths.apache_socket
)
except (OSError, ValueError, KeyboardInterrupt):
for path, target in previous.items():
replace_symlink(path, target)
if previous:
reload_apache()
raise
def install_uploaded_certificate(site, chain, key):
with locked_web_node(fcntl.LOCK_EX):
paths = SitePaths.for_site(site)
check_https_prerequisites(site, paths)
apache, enabled = https_paths(paths)
previous_config = None
if os.path.lexists(apache):
check_configuration(
apache,
render_https_configuration(
site, socket_path=paths.apache_socket
),
)
previous_config = read_root_file(apache)
root = custom_lineage(site)
require_root_directory(root.parent, create_mode=0o700)
require_root_directory(root, create_mode=0o700)
active = root / "active"
previous = None
if os.path.lexists(active):
resolved_certificate_files(site)
previous = active.readlink()
revision = root / str(uuid4())
revision.mkdir(mode=0o700)
installed = False
created = []
tried_reload = False
try:
certificate, private = (
revision / "fullchain.pem",
revision / "privkey.pem",
)
write_new_file(certificate, chain, mode=0o600)
write_new_file(private, key, mode=0o600)
validate_certificate_files(site, certificate, private)
replace_symlink(active, revision.name)
new_config = render_https_configuration(
site, socket_path=paths.apache_socket
)
if previous_config is None:
write_new_file(apache, new_config, mode=0o644)
created.append(apache)
else:
replace_configuration(apache, new_config)
enable_apache_site(apache, enabled, created)
run("/usr/sbin/apache2ctl", "configtest")
tried_reload = True
run("/usr/sbin/service", "apache2", "reload")
installed = True
except (OSError, ValueError, KeyboardInterrupt):
if previous is None:
active.unlink(missing_ok=True)
else:
replace_symlink(active, previous)
for path in reversed(created):
path.unlink(missing_ok=True)
if previous_config is not None:
replace_configuration(apache, previous_config)
if tried_reload:
reload_apache()
raise
finally:
if not installed:
shutil.rmtree(revision)
if previous is not None:
shutil.rmtree(root / previous)
+30 -1
View File
@@ -194,6 +194,13 @@ class WebAliasRequest:
def parse_https_request(data):
if (
isinstance(data, dict)
and data.get("operation") == "manage_certificate"
):
from .web_certificates import WebCertificateRequest
return WebCertificateRequest.from_manifest(data)
if isinstance(data, dict) and "site" in data:
return WebAlias.from_manifest(data)
return WebSite.from_manifest(data)
@@ -536,10 +543,32 @@ def main(argv=None):
)
if args.command == "https-request":
from .web_certificates import (
CERTIFICATE_REQUEST_LIMIT,
WebCertificateRequest,
apply_website_certificate,
)
from .web_node_tls import provision_https
def certificate_request(spec):
if isinstance(spec, WebCertificateRequest):
return apply_website_certificate(spec)
return provision_https(spec)
def certificate_identity(spec):
return (
spec.identity()
if isinstance(spec, WebCertificateRequest)
else spec.manifest()
)
return serve_apply_request(
MANIFEST_VERSION, parse_https_request, provision_https
MANIFEST_VERSION,
parse_https_request,
certificate_request,
identity=certificate_identity,
include_result=True,
limit=CERTIFICATE_REQUEST_LIMIT,
)
if args.command == "sftp-keys-request":
+55 -19
View File
@@ -2,6 +2,7 @@ import fcntl
import os
import ssl
import subprocess
import uuid
from pathlib import Path
from .node_files import check_root_file, require_root_directory
@@ -41,7 +42,7 @@ def provision_https(site):
def ensure_certificate(site):
if os.path.lexists(certbot_lineage(site)):
if os.path.lexists(certificate_lineage(site)):
return
try:
require_root_directory(CERTBOT_ROOT)
@@ -59,12 +60,12 @@ def ensure_certificate(site):
request_certificate(site)
def request_certificate(site):
def request_certificate(site, *, force=False):
command = (
"/usr/bin/certbot",
"certonly",
"--non-interactive",
"--keep-until-expiring",
"--force-renewal" if force else "--keep-until-expiring",
"--webroot",
"--webroot-path",
str(ACME_WEBROOT),
@@ -162,27 +163,64 @@ def certbot_lineage(site):
return CERTBOT_ROOT / "live" / name
def https_configuration(site, *, socket_path=None):
lineage = certbot_lineage(site)
name = lineage.name
archive = CERTBOT_ROOT / "archive" / name
for directory in (lineage, archive):
def custom_lineage(site):
from .web_node_apply import STATE_DIRECTORY
return STATE_DIRECTORY / "certificates" / site.service_user
def certificate_lineage(site):
if not isinstance(site, WebAlias):
active = custom_lineage(site) / "active"
if os.path.lexists(active):
return active
return certbot_lineage(site)
def resolved_certificate_files(site):
lineage = certificate_lineage(site)
if lineage.name == "active":
require_root_directory(lineage.parent)
info = lineage.lstat()
try:
revision = uuid.UUID(os.readlink(lineage))
except (OSError, ValueError):
raise ValueError(
"The uploaded certificate directory is unexpected."
) from None
if info.st_uid != 0 or str(revision) != os.readlink(lineage):
raise ValueError(
"The uploaded certificate directory is unexpected."
)
archive = lineage.parent / str(revision)
lineage = archive
else:
archive = CERTBOT_ROOT / "archive" / lineage.name
for directory in {lineage, archive}:
try:
require_root_directory(directory)
except FileNotFoundError:
raise ValueError(
f"Obtain the Certbot certificate named {name}."
f"Obtain the certificate for {site.domain}."
) from None
certificate = lineage / "fullchain.pem"
private_key = lineage / "privkey.pem"
resolved = []
for source in (certificate, private_key):
for source in (lineage / "fullchain.pem", lineage / "privkey.pem"):
target = source.resolve(strict=True)
if target.parent != archive:
raise ValueError(f"Expected {source} to point into {archive}.")
raise ValueError(
"Expected certificate files to point into a managed folder."
)
resolved.append(target)
chain_file, key_file = resolved
return tuple(resolved)
def https_configuration(site, *, socket_path=None):
chain_file, key_file = resolved_certificate_files(site)
validate_certificate_files(site, chain_file, key_file)
return render_https_configuration(site, socket_path=socket_path)
def validate_certificate_files(site, chain_file, key_file):
check_root_file(chain_file)
check_root_file(key_file, mode=0o600)
try:
@@ -191,7 +229,7 @@ def https_configuration(site, *, socket_path=None):
)
except ssl.SSLError:
raise ValueError(
"Could not load the Certbot certificate and private key."
"Could not load the certificate and private key."
) from None
run(
"/usr/bin/openssl",
@@ -206,11 +244,9 @@ def https_configuration(site, *, socket_path=None):
str(chain_file),
)
return render_https_configuration(site, socket_path=socket_path)
def render_https_configuration(site, *, socket_path=None):
lineage = certbot_lineage(site)
lineage = certificate_lineage(site)
certificate = lineage / "fullchain.pem"
private_key = lineage / "privkey.pem"
return site.render(