Merge pull request 'Add restricted SFTP access and SSH key management' (#22) from feature/site-sftp into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s

Reviewed-on: #22
This commit was merged in pull request #22.
This commit is contained in:
parkel committed 2026-11-21 10:57:13 +01:00
commit 3ce2184885
26 files changed
+1067 -21

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
Match Group coulobre-sftp
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthorizedKeysFile /etc/ssh/coulobre-authorized-keys/%u
AuthorizedKeysCommand none
TrustedUserCAKeys none
ChrootDirectory %h
ForceCommand internal-sftp -d /public -u 0022 -P symlink,hardlink
DisableForwarding yes
PermitTunnel no
PermitTTY no
PermitUserRC no
Match all
+1
View File
@@ -10,6 +10,7 @@ COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_WEB_ACTIVATION=1
# COULOBRE_LOCAL_WEB_HTTPS=1
# COULOBRE_LOCAL_WEB_SFTP=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
+14
View File
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre local SFTP key socket
[Socket]
ListenStream=/run/coulobre-sftp-apply.sock
SocketUser=root
SocketGroup=coulobre-sftp-provisioning
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,18 @@
[Unit]
Description=Coulobre local SFTP key request
After=ssh.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
UMask=0022
ExecStart=/opt/coulobre/bin/coulobre-web-node sftp-keys-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=3min
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel SFTP key worker
Requires=coulobre-sftp-apply.socket
Wants=network-online.target
After=network-online.target coulobre-sftp-apply.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-sftp-provisioner
Group=coulobre-sftp-provisioner
SupplementaryGroups=coulobre-sftp-provisioning
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-web-sftp --hostname=sftp-provisioner@%H --concurrency=1
KillMode=mixed
TimeoutStopSec=4min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
+51
View File
@@ -261,6 +261,57 @@ and the expected lineage name. The panel can then enable HTTPS using
that certificate. Certbot renews it with its saved authenticator.
[Certbot DNS plugins](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins)
## Set up SFTP access for hosted websites
Use OpenSSH on the local web node. The site account starts in `/public`
inside its hosting directory. OpenSSH allows public key authentication
and restricts the connection to file transfers.
[OpenSSH server configuration](https://man.openbsd.org/sshd_config)
```sh
sudo apt install openssh-server
sudo groupadd --system coulobre-sftp
sudo install -d -m 0755 /etc/ssh/coulobre-authorized-keys
sudo install -m 0644 deploy/openssh/coulobre-sftp.conf.example \
/etc/ssh/sshd_config.d/00-coulobre-sftp.conf
sudo sshd -t
sudo systemctl reload-or-restart ssh.service
```
Install the worker and socket to manage keys from the panel.
```sh
sudo groupadd --system coulobre-sftp-provisioning
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-sftp-provisioner
sudo install -m 0644 deploy/systemd/coulobre-sftp-apply.socket \
deploy/systemd/coulobre-sftp-apply@.service \
deploy/systemd/coulobre-sftp-provisioner.service /etc/systemd/system/
sudo systemctl daemon-reload
```
Set `COULOBRE_LOCAL_WEB_SFTP=1` in `/etc/coulobre/panel.env`, then apply
pending migrations and restart the panel services.
```sh
panel_manage migrate --noinput
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
sudo systemctl enable --now coulobre-sftp-apply.socket \
coulobre-sftp-provisioner.service
```
On an active hosting account, open **SFTP access**. Assigned customers
can manage keys for their accounts. Operators need **Can view hosting
account** and **Can change site SFTP access**.
Select one or more `.pub` files to add keys to the hosting account.
A file can contain one OpenSSH public key per line. Each key has its own
fingerprint and **Remove key** action. Use **Revoke SFTP access** to
remove all keys for new connections. Revoke access and close any existing
SFTP sessions before transferring the hosting account to another customer.
Connect to the web node's SSH hostname and port, which may differ from
the hostname that a reverse proxy uses for web traffic.
## Provision local databases from the panel
Enable the [database provisioning socket](development.md#enable-local-database-provisioning)
+23
View File
@@ -754,6 +754,29 @@ read the JSON reply to EOF. A `configured` reply includes the account ID and
domain. A `failed` reply includes a diagnostic in `problem`. Retry the same
manifest if the connection closes before a reply arrives.
## Install SFTP keys on a web node
Generate an Ed25519 key on the computer that will connect and choose a
passphrase when prompted. With the default filename,
`~/.ssh/id_ed25519.pub` is the public key file. Keep the private key on
that computer.
```sh
ssh-keygen -t ed25519
```
Enable the OpenSSH configuration on the web node and apply the site's
deployment manifest. Use the public key file to set the account's keys
directly on that node. Running the command with an empty file removes
the configured keys for new connections.
[SFTP deployment setup](deployment.md#set-up-sftp-access-for-hosted-websites)
```sh
sudo /opt/coulobre/bin/coulobre-web-node set-sftp-keys \
coulobre-web-plan-1.json site-access.pub
sftp coulobre-1@web-node.example.org
```
## Run an isolated PHP test site
Open a completed preview for the account's current domain and select **Download
+1
View File
@@ -20,6 +20,7 @@ PREVIEW_VIEWS = frozenset(
"panel:account",
"panel:database_create",
"panel:mailbox_create",
"panel:sftp_keys",
}
)
EndReason = CustomerImpersonation.EndReason
@@ -0,0 +1,62 @@
# Generated by Django 5.2.19 on 2026-11-21 09:38
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0018_web_https"),
]
operations = [
migrations.CreateModel(
name="SiteSFTP",
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)),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("public_keys", models.TextField(blank=True)),
(
"requested_customer_id",
models.PositiveBigIntegerField(blank=True, null=True),
),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="sftp",
to="hosting.hostingaccount",
),
),
],
options={
"verbose_name": "site SFTP access",
"verbose_name_plural": "site SFTP access",
},
),
]
+15
View File
@@ -352,6 +352,21 @@ class WebHTTPS(ProvisioningJob):
verbose_name = "website HTTPS request"
class SiteSFTP(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp"
)
domain = DomainNameField(max_length=253)
public_keys = models.TextField(blank=True)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
class Meta:
verbose_name = "site SFTP access"
verbose_name_plural = "site SFTP access"
class DatabaseProvisioning(ProvisioningJob):
database = models.OneToOneField(
HostingDatabase, on_delete=models.CASCADE, related_name="provisioning"
+10
View File
@@ -16,6 +16,16 @@ def enable_local_https(site):
)
def update_local_sftp(keys):
apply_on_local_node(
keys,
"/run/coulobre-sftp-apply.sock",
"web node",
"SFTP key request",
identity=keys.identity(),
)
def provision_local_database(database):
apply_on_local_node(
database,
+136
View File
@@ -0,0 +1,136 @@
from django import forms
from django.core.exceptions import ValidationError
from django.db import transaction
from coulobre.sftp_keys import (
MAX_KEYS_BYTES,
public_key_fingerprint,
read_public_keys,
)
from .access import customer_for_user, is_tenant
from .models import SiteSFTP
from .resource_requests import lock_hosting_account
def can_manage_sftp(user):
return customer_for_user(user) is not None or (
not is_tenant(user)
and user.has_perms(
("hosting.view_hostingaccount", "hosting.change_sitesftp")
)
)
def site_is_active(account):
return account.webprovisioningplan_set.filter(
primary_domain=account.primary_domain,
activation__finished_at__isnull=False,
activation__problem="",
).exists()
@transaction.atomic
def queue_sftp_keys(
account_id, operation, *, public_keys="", fingerprint="", customer_id=None
):
account = lock_hosting_account(account_id, customer_id)
request = SiteSFTP.objects.filter(account=account).first()
previous = request.public_keys if request is not None else ""
keys = change_key_list(previous, operation, public_keys, fingerprint)
if operation == "remove" and keys == previous:
return
if keys and not site_is_active(account):
raise ValidationError(
"Activate the site for the current domain first."
)
if not keys and request is None:
return
updates = {
"domain": account.primary_domain if keys else request.domain,
"public_keys": keys,
"requested_customer_id": customer_id,
}
if request is None:
SiteSFTP.objects.create(account=account, **updates)
return
same_keys = (
request.domain == updates["domain"]
and request.public_keys == keys
and request.requested_customer_id == customer_id
)
if request.finished_at is None:
if not same_keys:
raise ValidationError(
"Wait for the current SFTP key request to finish."
)
elif not same_keys or request.problem:
SiteSFTP.objects.requeue(
SiteSFTP.objects.filter(pk=request.pk), **updates
)
def change_key_list(previous, operation, public_keys, fingerprint):
if operation == "revoke":
return ""
if operation == "remove":
return "".join(
f"{key}\n"
for key in previous.splitlines()
if public_key_fingerprint(key) != fingerprint
)
return merge_public_keys(previous, public_keys)
def merge_public_keys(*lists):
keys = dict.fromkeys(key for keys in lists for key in keys.splitlines())
value = "".join(f"{key}\n" for key in keys)
if len(value.encode("utf-8")) > MAX_KEYS_BYTES:
raise ValidationError("The site's SSH key list exceeds 16 KiB.")
return value
class PublicKeyFileInput(forms.FileInput):
allow_multiple_selected = True
class SFTPKeyUploadForm(forms.Form):
operation = forms.ChoiceField(
choices=(("add", "Add"), ("remove", "Remove"), ("revoke", "Revoke"))
)
fingerprint = forms.RegexField(
r"\ASHA256:[A-Za-z0-9+/]{43}\Z", required=False
)
public_keys = forms.Field(
label="SSH public key files",
required=False,
widget=PublicKeyFileInput,
help_text="Choose .pub files or a list with one public key per line.",
)
def clean(self):
cleaned = super().clean()
if cleaned.get("operation") == "remove" and not cleaned.get(
"fingerprint"
):
self.add_error(None, "Select an SSH key to remove.")
if cleaned.get("operation") != "add":
cleaned["public_keys"] = ""
return cleaned
uploads = cleaned.get("public_keys")
if not uploads:
self.add_error("public_keys", "Choose an SSH public key file.")
return cleaned
try:
keys = merge_public_keys(
*(read_public_keys(file) for file in uploads)
)
if not keys:
raise ValueError("The files do not contain an SSH public key.")
except ValueError as error:
self.add_error("public_keys", str(error))
except ValidationError as error:
self.add_error("public_keys", error)
else:
cleaned["public_keys"] = keys
return cleaned
+38
View File
@@ -6,12 +6,14 @@ from django.db.models import Q
from django.utils import timezone
from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite
from .models import (
DatabaseProvisioning,
DnsPublication,
MailboxProvisioning,
SiteSFTP,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
@@ -22,11 +24,14 @@ from .node_client import (
provision_local_database,
provision_local_mailbox,
publish_local_zone,
update_local_sftp,
)
from .sftp import site_is_active
REDISPATCH_AFTER = timedelta(minutes=5)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https"
WEB_SFTP_QUEUE = "coulobre-web-sftp"
DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning"
DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing"
MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning"
@@ -81,6 +86,12 @@ def dispatch_web_https():
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
@shared_task
def dispatch_web_sftp():
if settings.LOCAL_WEB_SFTP:
dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE)
@shared_task
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
@@ -169,6 +180,33 @@ def apply_web_https(provisioning):
enable_local_https(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def update_web_sftp(request_id):
if settings.LOCAL_WEB_SFTP:
run_provisioning_job(
SiteSFTP.objects.select_related("account__customer__user"),
request_id,
apply_web_sftp,
"Could not contact the local SFTP service. "
"Check its socket and try again.",
)
def apply_web_sftp(request):
account = request.account
if request.requested_customer_id is not None and (
request.requested_customer_id != account.customer_id
or not account.customer.user.is_active
):
raise ValueError("The customer no longer has access to this account.")
if request.public_keys and (
request.domain != account.primary_domain or not site_is_active(account)
):
raise ValueError("Activate the site for the current domain first.")
site = WebSite(request.account_id, request.domain)
update_local_sftp(SFTPKeys(site, request.public_keys))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database(provisioning_id):
if settings.LOCAL_DATABASE_PROVISIONING:
@@ -7,8 +7,15 @@
<h1>{{ account.name }}</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
{% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% if manage_sftp or is_operator and perms.hosting.change_hostingaccount %}
<div class="form-actions">
{% if manage_sftp %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
{% endif %}
{% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% endif %}
</div>
{% endif %}
</header>
<dl class="details surface">
@@ -0,0 +1,95 @@
{% extends "hosting/base.html" %}
{% block title %}SFTP access · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>SFTP access</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
{% if account.sftp and not account.sftp.finished_at %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">Refresh status</a>
{% endif %}
</header>
{% with request_status=account.sftp %}
{% if request_status %}
<p class="notice">
{% if request_status.state == "configured" %}
{% if request_status.public_keys %}SSH keys installed.{% else %}SFTP access revoked.{% endif %}
{% elif request_status.state == "failed" %}
{{ request_status.problem }}
{% elif request_status.state == "running" %}
Applying SSH keys.
{% else %}
SSH key request queued.
{% endif %}
</p>
{% endif %}
<section class="surface editor-surface" aria-labelledby="key-instructions">
<div class="editor">
<h2 id="key-instructions">Generate an SSH key</h2>
<p>Run this command on your computer.</p>
<pre><code>ssh-keygen -t ed25519</code></pre>
<p>Choose a passphrase when prompted. Use a different filename if you already have a key. With the default filename, upload <code>~/.ssh/id_ed25519.pub</code>. Keep the private key on your computer.</p>
<p>Use the web node's SSH hostname and port with the username <code>coulobre-{{ account.pk }}</code>. The SFTP session starts in <code>/public</code>.</p>
</div>
</section>
{{ form.non_field_errors }}
{{ form.operation.errors }}
{{ form.fingerprint.errors }}
{% if ssh_keys %}
<section class="surface" aria-labelledby="ssh-keys-heading">
<header class="section-heading">
<div>
<h2 id="ssh-keys-heading">SSH keys</h2>
<p class="heading-meta">Run <code>ssh-keygen -lf ~/.ssh/id_ed25519.pub</code> to check a key's fingerprint.</p>
</div>
</header>
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Key type</th>
<th scope="col">Fingerprint</th>
{% if can_edit_keys %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
{% for key_type, fingerprint in ssh_keys %}
<tr>
<td>{{ key_type }}</td>
<td class="domain">{{ fingerprint }}</td>
{% if can_edit_keys %}
<td>
<form method="post">
{% csrf_token %}
<input type="hidden" name="fingerprint" value="{{ fingerprint }}">
<button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button>
</form>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% endif %}
{% if can_edit_keys or can_revoke_keys %}
<section class="surface editor-surface" aria-label="SSH key management">
<form class="editor" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if can_edit_keys %}
{{ form.public_keys.as_field_group }}
{% endif %}
<div class="form-actions">
{% if can_edit_keys %}<button class="button primary" type="submit" name="operation" value="add">Upload SSH keys</button>{% endif %}
{% if can_revoke_keys %}
<button class="button secondary" type="submit" name="operation" value="revoke">Revoke SFTP access</button>
{% endif %}
</div>
</form>
</section>
{% endif %}
{% endwith %}
{% endblock %}
+58
View File
@@ -0,0 +1,58 @@
import json
from base64 import b64encode
from contextlib import redirect_stdout
from io import BytesIO, StringIO
from types import SimpleNamespace
from unittest.mock import patch
from django.test import SimpleTestCase
from coulobre.sftp_keys import SFTPKeys, read_public_keys
from coulobre.web_node import WebSite, main
def public_key(byte=1):
header = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20"
return "ssh-ed25519 " + b64encode(header + bytes([byte]) * 32).decode()
class SFTPManifestTests(SimpleTestCase):
def test_public_key_list_discards_comments_and_duplicates(self):
key = public_key()
source = BytesIO(f"# heading\n{key} admin\n{key} duplicate\n".encode())
self.assertEqual(read_public_keys(source), f"{key}\n")
def test_rejects_private_keys_options_and_oversized_input(self):
for content in (
b"-----BEGIN OPENSSH PRIVATE KEY-----\n",
f'restrict,command="whoami" {public_key()}'.encode(),
b"ssh-ed25519 not-a-blob",
b" " * (16 * 1024 + 1),
):
with (
self.subTest(length=len(content)),
self.assertRaises(ValueError),
):
read_public_keys(BytesIO(content))
def test_request_returns_identity_and_status_without_the_key(self):
site = WebSite(42, "example.org")
request = SFTPKeys(site, public_key())
output = StringIO()
with (
patch(
"sys.stdin",
SimpleNamespace(
buffer=BytesIO(json.dumps(request.manifest()).encode())
),
),
patch("coulobre.web_node_sftp.apply_sftp_keys") as apply,
redirect_stdout(output),
):
self.assertEqual(main(["sftp-keys-request"]), 0)
apply.assert_called_once_with(request)
self.assertEqual(
json.loads(output.getvalue()),
site.manifest() | {"state": "configured", "problem": None},
)
+164
View File
@@ -0,0 +1,164 @@
from unittest.mock import patch
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 coulobre.sftp_keys import public_key_fingerprint
from .models import (
Customer,
HostingAccount,
SiteSFTP,
WebActivation,
WebProvisioningPlan,
)
from .tasks import update_web_sftp
from .test_sftp_keys import public_key
@override_settings(LOCAL_WEB_SFTP=True)
class SiteSFTPTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.alice = users.create_user("alice")
cls.customer = Customer.objects.create(user=cls.alice)
cls.account = HostingAccount.objects.create(
name="Alice site",
primary_domain="alice.example",
customer=cls.customer,
)
plan = WebProvisioningPlan.for_account(cls.account)
plan.save()
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
def setUp(self):
self.client.force_login(self.alice)
self.url = reverse("panel:sftp_keys", args=[self.account.pk])
def upload(self, key, url=None):
return self.client.post(
url or self.url,
{
"operation": "add",
"public_keys": SimpleUploadedFile("site.pub", key.encode()),
},
)
def test_customer_can_upload_a_public_key_and_track_installation(self):
self.assertContains(
self.client.get(self.account.get_absolute_url()), "SFTP access"
)
page = self.client.get(self.url)
self.assertContains(page, "ssh-keygen -t ed25519")
self.assertContains(page, f"coulobre-{self.account.pk}")
key = public_key()
self.assertRedirects(self.upload(key), self.url)
job = SiteSFTP.objects.get(account=self.account)
self.assertEqual(job.requested_customer_id, self.customer.pk)
self.assertContains(
self.client.get(self.url), "SSH key request queued."
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
self.assertEqual(apply.call_args.args[0].public_keys, f"{key}\n")
self.assertContains(self.client.get(self.url), "SSH keys installed.")
def test_adds_separate_uploads_and_removes_only_the_selected_key(self):
first, second, third = (public_key(number) for number in (1, 2, 3))
self.assertRedirects(self.upload(first), self.url)
job = SiteSFTP.objects.get(account=self.account)
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
response = self.client.post(
self.url,
{
"operation": "add",
"public_keys": [
SimpleUploadedFile("second.pub", second.encode()),
SimpleUploadedFile(
"third.pub", f"{third}\n{first}".encode()
),
],
},
)
self.assertRedirects(response, self.url)
job.refresh_from_db()
self.assertEqual(job.public_keys.splitlines(), [first, second, third])
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
fingerprint = public_key_fingerprint(second)
self.assertContains(self.client.get(self.url), fingerprint)
self.assertRedirects(
self.client.post(
self.url, {"operation": "remove", "fingerprint": fingerprint}
),
self.url,
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
self.assertEqual(
apply.call_args.args[0].public_keys.splitlines(), [first, third]
)
def test_customer_cannot_upload_to_another_account(self):
other = HostingAccount.objects.create(
name="Other site", primary_domain="other.example"
)
url = reverse("panel:sftp_keys", args=[other.pk])
self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.upload(public_key(), url).status_code, 404)
self.assertFalse(SiteSFTP.objects.exists())
def test_rejects_private_keys_before_queueing(self):
response = self.upload("-----BEGIN OPENSSH PRIVATE KEY-----\n")
self.assertContains(response, "Expected a supported SSH public key")
self.assertNotContains(response, "BEGIN OPENSSH PRIVATE KEY")
self.assertFalse(SiteSFTP.objects.exists())
def test_customer_preview_can_read_instructions_and_cannot_upload(self):
operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(operator)
start = reverse("panel:impersonation_start", args=[self.customer.pk])
self.client.post(start)
response = self.client.get(self.url)
self.assertContains(response, "ssh-keygen -t ed25519")
self.assertNotContains(response, "Upload SSH keys")
self.assertEqual(self.upload(public_key()).status_code, 403)
self.assertFalse(SiteSFTP.objects.exists())
def test_worker_checks_customer_assignment_before_installing_keys(self):
self.upload(public_key())
job = SiteSFTP.objects.get(account=self.account)
HostingAccount.objects.filter(pk=self.account.pk).update(customer=None)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
apply.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertIn("no longer has access", job.problem)
def test_revokes_at_the_original_node_after_a_domain_change(self):
self.upload(public_key())
job = SiteSFTP.objects.get(account=self.account)
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="new.example"
)
self.assertContains(self.client.get(self.url), "Revoke SFTP access")
self.assertRedirects(
self.client.post(self.url, {"operation": "revoke"}), self.url
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
keys = apply.call_args.args[0]
self.assertEqual(keys.site.domain, "alice.example")
self.assertEqual(keys.public_keys, "")
self.assertContains(self.client.get(self.url), "SFTP access revoked.")
+5 -1
View File
@@ -50,7 +50,11 @@ class WebNodeTLSTests(SimpleTestCase):
patch("coulobre.web_node_tls.os.geteuid", return_value=0)
)
self.enterContext(
patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state)
patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state)
)
self.enterContext(patch("coulobre.web_node_apply.check_root_file"))
self.enterContext(
patch("coulobre.web_node_apply.require_root_directory")
)
self.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot))
self.webroot = directory / "coulobre-acme"
+5
View File
@@ -20,6 +20,11 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/sftp/",
views.SiteSFTPKeys.as_view(),
name="sftp_keys",
),
path(
"accounts/<int:pk>/edit/",
views.AccountEdit.as_view(),
+74
View File
@@ -28,6 +28,7 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.sftp_keys import public_key_fingerprint
from .access import (
OperatorOnlyMixin,
@@ -60,6 +61,12 @@ from .models import (
)
from .reseller_accounts import create_reseller_account
from .resource_requests import create_database_request, create_mailbox_request
from .sftp import (
SFTPKeyUploadForm,
can_manage_sftp,
queue_sftp_keys,
site_is_active,
)
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
@@ -222,6 +229,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
reseller = reseller_for_user(user)
customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP
and can_manage_sftp(user)
and (site_is_active(self.object) or hasattr(self.object, "sftp"))
)
if reseller is not None or (
customer is None and user.has_perm(VIEW_PLANS)
):
@@ -264,6 +276,68 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
return context
class SiteSFTPKeys(PermissionRequiredMixin, FormView):
form_class = SFTPKeyUploadForm
template_name = "hosting/sftp_keys.html"
def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_SFTP:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_sftp(self.request.user)
@cached_property
def account(self):
accounts = HostingAccount.objects.select_related("sftp")
customer = customer_for_user(self.request.user)
if customer is not None:
accounts = accounts.filter(customer=customer)
return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs):
status = getattr(self.account, "sftp", None)
editable = getattr(self.request, "impersonation", None) is None
idle = status is None or status.finished_at is not None
keys = () if status is None else status.public_keys.splitlines()
return super().get_context_data(
account=self.account,
ssh_keys=[
(key.split(" ", 1)[0], public_key_fingerprint(key))
for key in keys
],
can_edit_keys=editable and idle and site_is_active(self.account),
can_revoke_keys=editable
and idle
and status is not None
and bool(status.public_keys or status.problem),
**kwargs,
)
def get_success_url(self):
return reverse("panel:sftp_keys", args=[self.account.pk])
def form_valid(self, form):
customer = customer_for_user(self.request.user)
try:
queue_sftp_keys(
self.account.pk,
form.cleaned_data["operation"],
public_keys=form.cleaned_data["public_keys"],
fingerprint=form.cleaned_data["fingerprint"],
customer_id=customer.pk if customer is not None else None,
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.render_to_response(
self.get_context_data(form=form), status=409
)
return super().form_valid(form)
class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
queryset = Customer.objects.select_related(
"user__hosting_reseller"
+7
View File
@@ -120,6 +120,7 @@ CELERY_TASK_DEFAULT_QUEUE = "coulobre"
CELERY_TASK_IGNORE_RESULT = True
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
)
@@ -146,6 +147,12 @@ if LOCAL_WEB_HTTPS:
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_WEB_SFTP:
CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = {
"task": "coulobre.hosting.tasks.dispatch_web_sftp",
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_DATABASE_PROVISIONING:
CELERY_BEAT_SCHEDULE["dispatch-database-provisioning"] = {
"task": "coulobre.hosting.tasks.dispatch_database_provisioning",
+91
View File
@@ -0,0 +1,91 @@
from base64 import b64decode, b64encode
from binascii import Error
from dataclasses import dataclass
from hashlib import sha256
from .web_node import WebSite
MAX_KEYS_BYTES = 16 * 1024
KEY_TYPES = frozenset(
{
"ssh-ed25519",
"ssh-rsa",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
}
)
def read_public_keys(source):
body = source.read(MAX_KEYS_BYTES + 1)
if len(body) > MAX_KEYS_BYTES:
raise ValueError("The SSH public key list exceeds 16 KiB.")
try:
return normalize_public_keys(body.decode("utf-8"))
except UnicodeError:
raise ValueError("Expected a UTF-8 SSH public key list.") from None
def normalize_public_keys(value):
if (
not isinstance(value, str)
or len(value.encode("utf-8")) > MAX_KEYS_BYTES
):
raise ValueError("Expected an SSH public key list of up to 16 KiB.")
keys = {}
for number, line in enumerate(value.splitlines(), 1):
parts = line.split(None, 2)
if not parts or parts[0].startswith("#"):
continue
if len(parts) < 2 or parts[0] not in KEY_TYPES:
raise ValueError(
f"Expected a supported SSH public key on line {number}."
)
key_type, encoded = parts[:2]
prefix = len(key_type).to_bytes(4) + key_type.encode("ascii")
try:
raw = b64decode(encoded, validate=True)
except (Error, ValueError):
raw = b""
if not raw.startswith(prefix) or len(raw) <= len(prefix):
raise ValueError(f"Invalid SSH public key on line {number}.")
keys[f"{key_type} {b64encode(raw).decode('ascii')}"] = None
return "".join(f"{key}\n" for key in keys)
def public_key_fingerprint(key):
_, encoded = key.split(" ", 1)
digest = sha256(b64decode(encoded, validate=True)).digest()
return "SHA256:" + b64encode(digest).decode("ascii").rstrip("=")
@dataclass(frozen=True)
class SFTPKeys:
site: WebSite
public_keys: str
def __post_init__(self):
object.__setattr__(
self, "public_keys", normalize_public_keys(self.public_keys)
)
@classmethod
def from_manifest(cls, payload):
if not isinstance(payload, dict) or "public_keys" not in payload:
raise ValueError("Expected a site manifest with SSH public keys.")
site = WebSite.from_manifest(
{
key: value
for key, value in payload.items()
if key != "public_keys"
}
)
return cls(site, payload["public_keys"])
def manifest(self):
return self.site.manifest() | {"public_keys": self.public_keys}
def identity(self):
return self.site.manifest()
+27
View File
@@ -108,6 +108,16 @@ def main(argv=None):
"https-status", help="Check a site's local HTTPS configuration."
)
https_status.add_argument("manifest", type=Path)
sftp = commands.add_parser(
"set-sftp-keys",
help="Set the SSH public keys for a site's SFTP login.",
)
sftp.add_argument("manifest", type=Path)
sftp.add_argument("public_keys", type=Path)
commands.add_parser(
"sftp-keys-request",
help="Apply one SFTP key request from standard input.",
)
restore = commands.add_parser(
"restore-directadmin",
help="Restore a DirectAdmin website into an empty web root.",
@@ -133,6 +143,18 @@ def main(argv=None):
MANIFEST_VERSION, WebSite.from_manifest, provision_https
)
if args.command == "sftp-keys-request":
from .sftp_keys import MAX_KEYS_BYTES, SFTPKeys
from .web_node_sftp import apply_sftp_keys
return serve_apply_request(
MANIFEST_VERSION,
SFTPKeys.from_manifest,
apply_sftp_keys,
limit=MAX_KEYS_BYTES + 4096,
identity=SFTPKeys.identity,
)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload)
@@ -158,6 +180,11 @@ def main(argv=None):
report = https_status(site)
print(json.dumps(report, indent=2))
return 0 if report["state"] == "configured" else 2
elif args.command == "set-sftp-keys":
from .web_node_sftp import set_sftp_keys
user, count = set_sftp_keys(site, args.public_keys)
print(f"Installed {count} SFTP public key(s) for {user}.")
elif args.command == "restore-directadmin":
from .web_node_restore import restore_website
+21 -1
View File
@@ -10,7 +10,12 @@ from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from .node_files import read_root_file, require_root_directory, write_new_file
from .node_files import (
check_root_file,
read_root_file,
require_root_directory,
write_new_file,
)
STATE_DIRECTORY = Path("/var/lib/coulobre/web-node")
WEB_ROOT = Path("/srv/coulobre/web")
@@ -42,6 +47,21 @@ class SitePaths:
)
@contextmanager
def locked_web_node(mode):
try:
require_root_directory(STATE_DIRECTORY)
except FileNotFoundError:
raise ValueError(
"Apply the site manifest on the web node first."
) from None
lock_path = STATE_DIRECTORY / "apply.lock"
check_root_file(lock_path)
with lock_path.open("r") as lock:
fcntl.flock(lock, mode)
yield
def apply_site(site):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the web node.")
+99
View File
@@ -0,0 +1,99 @@
import fcntl
import os
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from .node_files import check_root_file, require_root_directory, write_new_file
from .sftp_keys import SFTPKeys, read_public_keys
from .web_node_apply import (
SitePaths,
check_installation,
check_reservation,
current_group,
locked_web_node,
run,
)
SFTP_GROUP = "coulobre-sftp"
AUTHORIZED_KEYS = Path("/etc/ssh/coulobre-authorized-keys")
def set_sftp_keys(site, public_keys):
with public_keys.open("rb") as source:
return apply_sftp_keys(SFTPKeys(site, read_public_keys(source)))
def apply_sftp_keys(request):
if os.geteuid() != 0:
raise ValueError("Run set-sftp-keys as root on the web node.")
site = request.site
keys = request.public_keys.splitlines()
for number, key in enumerate(keys, 1):
validate_public_key(key, number)
require_root_directory(AUTHORIZED_KEYS)
user = site.configuration()["service_user"]
target = AUTHORIZED_KEYS / user
with locked_web_node(fcntl.LOCK_EX):
check_reservation(site)
if os.path.lexists(target):
check_root_file(target, mode=0o644)
if keys:
check_installation(site, SitePaths.for_site(site))
group = current_group(SFTP_GROUP)
if group is None or not group.gr_gid:
raise ValueError(f"Create the {SFTP_GROUP} group first.")
if user not in group.gr_mem:
run("/usr/sbin/usermod", "-a", "-G", SFTP_GROUP, user)
check_sshd(user)
with TemporaryDirectory(dir=AUTHORIZED_KEYS) as scratch:
staged = Path(scratch) / user
write_new_file(staged, request.public_keys, mode=0o644)
os.replace(staged, target)
return user, len(keys)
def validate_public_key(key, number):
try:
result = subprocess.run(
("/usr/bin/ssh-keygen", "-l", "-f", "-"),
input=f"{key}\n",
text=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
except subprocess.TimeoutExpired:
raise ValueError("SSH public key validation timed out.") from None
if result.returncode:
raise ValueError(f"Invalid SSH public key on line {number}.")
def check_sshd(user):
configuration = run(
"/usr/sbin/sshd",
"-T",
"-C",
f"user={user},host=localhost,addr=127.0.0.1",
)
required = {
"authenticationmethods publickey",
"pubkeyauthentication yes",
f"authorizedkeysfile {AUTHORIZED_KEYS}/%u",
"authorizedkeyscommand none",
"trustedusercakeys none",
"chrootdirectory %h",
"disableforwarding yes",
"permittty no",
"permituserrc no",
"permittunnel no",
"forcecommand internal-sftp -d /public -u 0022 -P symlink,hardlink",
}
if not required.issubset(configuration.splitlines()):
raise ValueError(
f"Configure the Coulobre OpenSSH restrictions for {user}."
)
+1 -17
View File
@@ -2,12 +2,10 @@ import fcntl
import os
import ssl
import subprocess
from contextlib import contextmanager
from pathlib import Path
from .node_files import check_root_file, require_root_directory
from .web_node_apply import (
STATE_DIRECTORY,
SitePaths,
check_configuration,
check_installation,
@@ -16,6 +14,7 @@ from .web_node_apply import (
configuration_installation,
enable_apache_site,
install_configuration,
locked_web_node,
run,
)
@@ -133,21 +132,6 @@ def https_status(site):
return {**report, "state": "configured"}
@contextmanager
def locked_web_node(mode):
try:
require_root_directory(STATE_DIRECTORY)
except FileNotFoundError:
raise ValueError(
"Apply the site manifest before enabling HTTPS."
) from None
lock_path = STATE_DIRECTORY / "apply.lock"
check_root_file(lock_path)
with lock_path.open("r") as lock:
fcntl.flock(lock, mode)
yield
def https_paths(paths):
name = f"{paths.apache.stem}-https.conf"
return paths.apache.with_name(name), paths.enabled.with_name(name)