Compare commits

..
5 Commits
Author SHA1 Message Date
parkel 7d380f093d Monitor SpamAssassin services on mail nodes
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 21:00:42 +01:00
parkel de9a560f6a Integrate SpamAssassin with Postfix mail delivery 2026-11-21 21:00:42 +01:00
parkel 3afdbb08ad Merge pull request 'Open the selected mailbox in Roundcube' (#73) from feature/roundcube-mailbox-signon 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: #73
2026-11-21 20:52:27 +01:00
parkel 653d365645 Document and package the Roundcube sign-on plugin
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 20:18:11 +01:00
parkel 07b26838c9 Add mailbox-scoped sign-on for Roundcube 2026-11-21 20:18:05 +01:00
26 changed files with 974 additions and 87 deletions

No files matched your search

+2
View File
@@ -25,6 +25,8 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_MAIL_IMAP_HOST=mail.example.org
# COULOBRE_PHPMYADMIN_URL=https://tools.example.org/phpmyadmin
# COULOBRE_PHPMYADMIN_BRIDGE_KEY=
# COULOBRE_ROUNDCUBE_URL=https://webmail.example.org
# COULOBRE_ROUNDCUBE_BRIDGE_KEY=
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_LOCAL_BACKUP_RETENTION=1
+23
View File
@@ -0,0 +1,23 @@
<VirtualHost *:443>
ServerName webmail.example.org
DocumentRoot /opt/roundcube/public_html
SSLEngine On
SSLCertificateFile /etc/ssl/coulobre-webmail/fullchain.pem
SSLCertificateKeyFile /etc/ssl/coulobre-webmail/privkey.pem
<Directory "/opt/roundcube/public_html">
Options FollowSymLinks
AllowOverride None
DirectoryIndex index.php
Require all granted
<FilesMatch "^(index|static)\.php$">
SetHandler "proxy:unix:/run/php/coulobre-roundcube.sock|fcgi://localhost/"
</FilesMatch>
<FilesMatch "^(?!(index|static)\.php$).*\.ph(?:p|ar|tml)$">
Require all denied
</FilesMatch>
</Directory>
</VirtualHost>
+12
View File
@@ -0,0 +1,12 @@
<?php
$config['plugins'][] = 'coulobre_webmail';
$config['coulobre_panel_origin'] = 'https://panel.example.org';
$config['coulobre_bridge_key_file'] = '/etc/coulobre-roundcube/bridge.key';
$config['imap_host'] = 'ssl://mail.example.org:993';
$config['imap_conn_options'] = [
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
];
$config['force_https'] = true;
$config['session_samesite'] = 'Lax';
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
/**
* Accept a single-use Coulobre ticket and use Roundcube's normal IMAP login.
*/
class coulobre_webmail extends rcube_plugin
{
private ?array $login = null;
public function init(): void
{
$this->add_hook('startup', [$this, 'startSignOn']);
$this->add_hook('authenticate', [$this, 'authenticateSignOn']);
}
public function startSignOn(array $args): array
{
if (!array_key_exists('_coulobre_ticket', $_POST)) {
return $args;
}
$roundcube = rcmail::get_instance();
$origin = $roundcube->config->get('coulobre_panel_origin', '');
if (
!is_string($origin)
|| preg_match('~\Ahttps://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $origin) !== 1
) {
$this->reject(503);
}
if (
($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST'
|| !rcube_utils::https_check()
|| ($_SERVER['HTTP_ORIGIN'] ?? '') !== $origin
) {
$this->reject(403);
}
$ticket = $_POST['_coulobre_ticket'];
if (
count($_POST) !== 1
|| !is_string($ticket)
|| preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $ticket) !== 1
) {
$this->reject(400);
}
// Use the configured mail service for the selected address.
$host = $roundcube->config->get('imap_host');
if (
!is_string($host)
|| preg_match('~\A(?:ssl|tls)://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $host) !== 1
) {
$this->reject(503);
}
$keyPath = $roundcube->config->get('coulobre_bridge_key_file', '');
$key = is_string($keyPath) && is_readable($keyPath)
? trim((string) @file_get_contents($keyPath, false, null, 0, 512))
: '';
if (
!function_exists('curl_init')
|| preg_match('/\A[A-Za-z0-9_-]{32,128}\z/D', $key) !== 1
) {
$this->reject(503);
}
$this->login = $this->exchangeTicket($origin, $key, $ticket);
$this->login['host'] = $host;
// Reset the previous mailbox session after the ticket is accepted.
$roundcube->kill_session();
return ['task' => 'login', 'action' => 'login'] + $args;
}
public function authenticateSignOn(array $args): array
{
if ($this->login === null) {
return $args;
}
$login = $this->login;
$this->login = null;
return [
'host' => $login['host'],
'user' => $login['user'],
'pass' => $login['password'],
'valid' => true,
// A first visit or a cross-site POST may have no Roundcube cookie.
'cookiecheck' => false,
] + $args;
}
private function exchangeTicket(string $origin, string $key, string $ticket): array
{
$connection = curl_init($origin . '/_bridge/roundcube/');
$body = '';
curl_setopt_array($connection, [
CURLOPT_POST => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
'X-Coulobre-Bridge-Key: ' . $key,
],
CURLOPT_POSTFIELDS => http_build_query(['ticket' => $ticket]),
CURLOPT_WRITEFUNCTION => static function ($connection, string $chunk) use (&$body): int {
if (strlen($body) + strlen($chunk) > 4096) {
return 0;
}
$body .= $chunk;
return strlen($chunk);
},
]);
$success = curl_exec($connection);
$status = curl_getinfo($connection, CURLINFO_RESPONSE_CODE);
if ($status === 404) {
$this->reject(403);
}
if (!$success || $status !== 200) {
$this->reject(503);
}
$login = json_decode($body, true);
if (
!is_array($login)
|| !is_string($login['user'] ?? null)
|| strlen($login['user']) > 254
|| preg_match('/\A[a-z0-9][a-z0-9._-]*@[a-z0-9.-]+\z/D', $login['user']) !== 1
|| !is_string($login['password'] ?? null)
|| preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $login['password']) !== 1
) {
$this->reject(502);
}
return $login;
}
private function reject(int $status): never
{
http_response_code($status);
header('Cache-Control: private, no-store');
header('Content-Type: text/plain; charset=UTF-8');
header('Referrer-Policy: no-referrer');
exit('Webmail sign-in could not be completed. Open the mailbox from Coulobre Panel again.');
}
}
+15
View File
@@ -0,0 +1,15 @@
[coulobre-roundcube]
user = coulobre-roundcube
group = coulobre-roundcube
listen = /run/php/coulobre-roundcube.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = ondemand
pm.max_children = 4
clear_env = yes
security.limit_extensions = .php
php_admin_flag[display_errors] = off
php_admin_flag[session.use_strict_mode] = on
php_admin_flag[session.cookie_secure] = on
php_admin_flag[session.cookie_httponly] = on
@@ -0,0 +1,3 @@
[Service]
PIDFile=/run/spamass/spamass.pid
RemainAfterExit=no
@@ -0,0 +1,2 @@
# Merge into /etc/postfix/main.cf. Keep any other smtpd_milters on this list.
smtpd_milters = { unix:spamass/spamass.sock, connect_timeout=3s, content_timeout=30s, default_action=accept }
@@ -0,0 +1,6 @@
# /etc/default/spamass-milter
# Tag mail without rewriting the subject or body. Skip authenticated SMTP.
OPTIONS="-m -I -- -d 127.0.0.1 -n 2 -t 15 --connect-retries=1"
SOCKET="/var/spool/postfix/spamass/spamass.sock"
SOCKETOWNER="spamass-milter:postfix"
SOCKETMODE="0660"
@@ -0,0 +1,2 @@
# /etc/default/spamd
OPTIONS="--listen=127.0.0.1 --allowed-ips=127.0.0.1 --username=debian-spamd --nouser-config --max-children=5 --timeout-child=15 --helper-home-dir=/var/lib/spamassassin"
+149 -3
View File
@@ -840,6 +840,76 @@ managed login. Existing database grants scope the session to the selected
database. Sign out of phpMyAdmin to end its session.
[phpMyAdmin signon mode](https://docs.phpmyadmin.net/en/latest/config.html#example-for-signon-authentication)
### Open a mailbox in Roundcube
On Ubuntu 26.04 with PHP 8.5, use the current Roundcube 1.7 Complete
release from [Roundcube Downloads](https://roundcube.net/download/). Verify
the archive and install Roundcube in `/opt/roundcube` following the
[upstream manual setup](https://github.com/roundcube/roundcubemail/wiki/Installation).
The Ubuntu 26.04 package at version 1.6.11 cannot start with PHP 8.5.
Install the required PHP extensions for Roundcube and its database, as
well as `php8.5-curl` for the bridge.
Use the mail server already configured for Coulobre. Confirm that a
mailbox can sign in over TLS using its full email address. Configure a
single IMAP host with a trusted certificate and configure Roundcube's SMTP
submission settings for sending mail. The same setup works with the panel's
local or remote [mailbox credential service](#enable-connection-details-for-remote-mailboxes).
Use a dedicated PHP-FPM account. Grant that account read access to the
Roundcube configuration and bridge key, access to the database, and write
access to the Roundcube temporary files and logs. Use the same account for
Roundcube maintenance jobs. Keep the application code and configuration
owned by root.
```sh
sudo useradd --system --user-group --no-create-home --shell /usr/sbin/nologin coulobre-roundcube
sudo install -d -o root -g coulobre-roundcube -m 0750 /etc/coulobre-roundcube
sudo install -o root -g coulobre-roundcube -m 0640 /dev/null /etc/coulobre-roundcube/bridge.key
sudo sh -c 'openssl rand -hex 32 > /etc/coulobre-roundcube/bridge.key'
sudo install -D -m 0644 deploy/roundcube/coulobre_webmail.php \
/opt/roundcube/plugins/coulobre_webmail/coulobre_webmail.php
sudo install -m 0644 deploy/roundcube/pool.conf.example \
/etc/php/8.5/fpm/pool.d/coulobre-roundcube.conf
sudo install -o root -g coulobre-roundcube -m 0640 deploy/roundcube/config.inc.php.example \
/etc/coulobre-roundcube/webmail.inc.php
sudoedit /etc/coulobre-roundcube/webmail.inc.php
```
Set the panel origin to the exact HTTPS origin users visit, including a
non-default port if one is used. Set `imap_host` to the mail server's TLS
endpoint. Include the example from the end of Roundcube's
`/opt/roundcube/config/config.inc.php`.
```php
require '/etc/coulobre-roundcube/webmail.inc.php';
```
Configure the webmail site with `deploy/roundcube/apache.conf.example`.
Substitute the hostname and certificate paths, enable Apache's `ssl` and
`proxy_fcgi` modules, and enable the site. The example serves
`/opt/roundcube/public_html` through the dedicated FPM socket and blocks
the web installer. Run the Apache configuration test and reload Apache
and PHP-FPM. Keep certificate verification enabled between Roundcube and
both the panel and the IMAP server.
On the panel, set the following values in `/etc/coulobre/panel.env`. Use the
same random key from `bridge.key` for Roundcube only. Set the webmail URL to
the canonical HTTPS base URL so a form POST can arrive without a redirect.
```ini
COULOBRE_ROUNDCUBE_URL=https://webmail.example.org
COULOBRE_ROUNDCUBE_BRIDGE_KEY=
```
Run `panel_manage migrate --noinput`, collect static files, and restart
`coulobre-panel`. Use **Open webmail** beside a mailbox in the account
view. The browser carries a single-use ticket valid for 45 seconds.
Roundcube exchanges the ticket with Coulobre over HTTPS and uses its
ordinary IMAP login. The exchange appears in **Service credential
accesses**. Opening another mailbox in the same browser switches the
current Roundcube session.
## Publish local DNS zones from the panel
To publish to BIND9 on another host, use the
@@ -923,6 +993,78 @@ Back up mail on the node that hosts the mailbox. The archive can be used to
recover messages and folders into a newly provisioned mailbox with the same
address. [Mailbox backup and restore](development.md#back-up-and-restore-a-mailbox)
## Filter incoming mail with SpamAssassin
Install the distribution's SpamAssassin and `spamass-milter` packages on
the host where Postfix receives mail. Use the same setup for a co-located
mail service and a separate mail node. A node shared by multiple Coulobre
installations needs one filter configuration.
```sh
sudo apt install spamassassin spamd spamc spamass-milter
sudo adduser spamass-milter postfix
sudoedit /etc/default/spamd /etc/default/spamass-milter /etc/postfix/main.cf
```
Use the settings from `deploy/spamassassin/spamd.default.example` and
`deploy/spamassassin/spamass-milter.default.example` in the corresponding
defaults files. The scanner listens on loopback and uses site-wide rules.
Postfix reaches the milter through a group-restricted socket inside its
queue directory.
Merge the `smtpd_milters` entry in
`deploy/spamassassin/postfix-main.cf.example` into the existing list. If a
receiving service overrides `smtpd_milters` in `master.cf`, add the entry
there too. The example skips authenticated SMTP and covers messages
received by an SMTP service configured with this milter. Deliveries from
the local `sendmail` command use Postfix's separate non-SMTP path.
[Postfix Milter setup](https://www.postfix.org/MILTER_README.html)
If Debian 13's `spamass-milter.service` is generated from
`/etc/init.d/spamass-milter`, install this drop-in so systemd tracks the
milter process.
```sh
sudo install -D -m 0644 deploy/spamassassin/debian-milter.service.conf \
/etc/systemd/system/spamass-milter.service.d/coulobre.conf
sudo systemctl daemon-reload
```
```sh
sudo spamassassin --lint
sudo systemctl enable spamd.service spamass-milter.service
sudo systemctl restart spamd.service spamass-milter.service
sudo postfix check
sudo postfix reload
```
The example delivers scanned messages with an `X-Spam-Status` header and
preserves the subject and body. Set the tagging threshold with
`required_score` in `/etc/spamassassin/local.cf`. Restart `spamd.service`
after editing its rules. The example lets Postfix accept mail during a
milter outage and lets the milter pass mail through during a scanner
outage. Messages above the `spamc` size limit also pass through unscanned.
The per-milter fallback preserves the failure policy of any other filter.
[SpamAssassin settings](https://spamassassin.apache.org/full/4.0.x/doc/Mail_SpamAssassin_Conf.html)
On a test mail node, check delivery through SMTP to a Coulobre mailbox and
inspect the full headers over IMAP.
1. Send a normal message and look for `X-Spam-Status: No`.
2. Send the [GTUBE test message](https://spamassassin.apache.org/gtube/)
and look for `X-Spam-Status: Yes` with `GTUBE` in the matched tests.
3. Stop `spamd.service` and send another test message. Confirm it arrives
without a scanner-added status. Start the scanner and repeat with
`spamass-milter.service` stopped. Start both services after testing.
Use `spamc -d 127.0.0.1 -K` to check the scanner from the mail node. Read
scan results with `journalctl -u spamd.service -u spamass-milter.service`
and Postfix's filter connection errors with `journalctl -t postfix/smtpd`
or in the mail log.
Add `spamd` and `spamass-milter` to the mail node's
[service health checks](#monitor-local-and-remote-services) to monitor the
two units.
## Provision mail and DNS on separate servers
Choose one destination per service. For example, run mail locally and publish
@@ -996,6 +1138,8 @@ Set up [BIND9](development.md#apply-a-zone-manifest) or
the corresponding [DNS socket](development.md#enable-local-dns-publishing) or
[mailbox socket](development.md#enable-local-mailbox-provisioning). The
destination runs the local socket service shipped with Coulobre.
[Enable SpamAssassin on the mail node](#filter-incoming-mail-with-spamassassin)
for incoming spam filtering.
Save the panel's public key from the previous step as `panel-node.pub` on
the destination. Create a receiver with only the socket group for that
@@ -1234,9 +1378,11 @@ COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apa
Choose an ID for each node using lower-case letters, numbers, and hyphens,
starting with a letter. Keep the IDs stable for the same hosts. List one
`local` node per panel installation and use `ssh` for each additional host.
Use `bind9`, `postfix`, and `dovecot` under `local` for co-located services.
Remote checks accept those same three service names. The SSH client matches
each remote node ID to a `Host` entry.
Use `bind9`, `postfix`, `dovecot`, `spamd`, and `spamass-milter` under
`local` for co-located services or under `ssh` for separate nodes. Only
list the spam filter units where filtering is configured. Update the
Coulobre package on a remote node before adding its filter units. The
SSH client matches each remote node ID to a `Host` entry.
Install the collector with a dedicated service identity after updating the
panel package.
@@ -0,0 +1,60 @@
# Generated by Django 5.2.19 on 2026-11-21 19:08
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0037_account_retirement"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AlterField(
model_name="servicecredentialaccess",
name="method",
field=models.CharField(
choices=[
("reveal", "Show connection details"),
("phpmyadmin", "phpMyAdmin"),
("webmail", "Roundcube"),
("rotate", "Rotate password"),
],
default="reveal",
max_length=10,
),
),
migrations.CreateModel(
name="RoundcubeGrant",
fields=[
(
"token_digest",
models.CharField(
max_length=64, primary_key=True, serialize=False
),
),
("expires_at", models.DateTimeField(db_index=True)),
("redeemed_at", models.DateTimeField(blank=True, null=True)),
("address", models.CharField(max_length=254)),
(
"actor",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
(
"mailbox",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingmailbox",
),
),
],
options={
"abstract": False,
},
),
]
+14 -2
View File
@@ -171,6 +171,7 @@ class ServiceCredentialAccess(models.Model):
class Method(models.TextChoices):
REVEAL = "reveal", "Show connection details"
PHPMYADMIN = "phpmyadmin", "phpMyAdmin"
WEBMAIL = "webmail", "Roundcube"
ROTATE = "rotate", "Rotate password"
method = models.CharField(
@@ -441,15 +442,26 @@ class HostingDatabase(models.Model):
return DatabaseSpec(self.account_id, self.suffix)
class PhpMyAdminGrant(models.Model):
class ServiceSignOnGrant(models.Model):
token_digest = models.CharField(max_length=64, primary_key=True)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE)
expires_at = models.DateTimeField(db_index=True)
redeemed_at = models.DateTimeField(null=True, blank=True)
class Meta:
abstract = True
class PhpMyAdminGrant(ServiceSignOnGrant):
database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE)
class RoundcubeGrant(ServiceSignOnGrant):
mailbox = models.ForeignKey("HostingMailbox", on_delete=models.CASCADE)
address = models.CharField(max_length=254)
class DirectAdminImport(models.Model):
account = models.OneToOneField(
+10 -56
View File
@@ -1,14 +1,6 @@
import hashlib
import hmac
import re
import secrets
from datetime import timedelta
from django.conf import settings
from django.db import transaction
from django.http import Http404, JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import (
@@ -27,9 +19,7 @@ from .service_credentials import (
enabled_credential_access,
fetch_service_credentials,
)
GRANT_LIFETIME = timedelta(seconds=45)
TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}")
from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant
def phpmyadmin_available(request):
@@ -52,52 +42,24 @@ class PhpMyAdminLaunch(DatabaseCredentialView):
def post(self, request, *args, **kwargs):
if not phpmyadmin_available(request):
raise Http404
token = issue_database_grant(request.user, self.resource)
token = issue_signon_grant(
PhpMyAdminGrant, request.user, database=self.resource
)
return render(
request,
"hosting/phpmyadmin_launch.html",
"hosting/service_signon.html",
{
"destination": settings.PHPMYADMIN_URL
+ "/coulobre-signon.php",
"ticket": token,
"database": self.resource.spec.name,
"product": "phpMyAdmin",
"resource": self.resource.spec.name,
"ticket_field": "ticket",
"account": self.account,
},
)
@sensitive_variables()
def issue_database_grant(actor, database):
now = timezone.now()
PhpMyAdminGrant.objects.filter(expires_at__lte=now).delete()
token = secrets.token_urlsafe(32)
PhpMyAdminGrant.objects.create(
token_digest=token_digest(token),
actor=actor,
database=database,
expires_at=now + GRANT_LIFETIME,
)
return token
@sensitive_variables()
def token_digest(token):
return hashlib.sha256(token.encode("ascii")).hexdigest()
@transaction.atomic
@sensitive_variables()
def consume_database_grant(token):
now = timezone.now()
digest = token_digest(token)
current = PhpMyAdminGrant.objects.filter(pk=digest)
if not current.filter(expires_at__gt=now, redeemed_at__isnull=True).update(
redeemed_at=now
):
return None
return current.select_related("actor", "database__account").first()
def actor_has_database_access(actor, database):
if database.account.retired_at is not None or not can_reveal_credentials(
actor, CredentialKind.DATABASE
@@ -115,16 +77,8 @@ def actor_has_database_access(actor, database):
def redeem_phpmyadmin(request):
if not phpmyadmin_available(request):
raise Http404
key = request.headers.get("X-Coulobre-Bridge-Key", "")
if not hmac.compare_digest(
key.encode("utf-8"), settings.PHPMYADMIN_BRIDGE_KEY.encode("utf-8")
):
raise Http404
token = request.POST.get("ticket", "")
if not TOKEN_PATTERN.fullmatch(token):
raise Http404
grant = consume_database_grant(token)
token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY)
grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account")
if grant is None or not actor_has_database_access(
grant.actor, grant.database
):
+156
View File
@@ -0,0 +1,156 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.http import Http404, JsonResponse
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import (
sensitive_post_parameters,
sensitive_variables,
)
from django.views.decorators.http import require_POST
from .access import customer_for_user
from .credential_views import MailboxCredentialView
from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess
from .service_credentials import (
CredentialKind,
CredentialOutcome,
can_reveal_credentials,
enabled_credential_access,
fetch_service_credentials,
)
from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant
def roundcube_available(request):
return bool(
settings.ROUNDCUBE_URL
and settings.ROUNDCUBE_BRIDGE_KEY
and enabled_credential_access(request, CredentialKind.MAILBOX)
)
def mailbox_can_open_webmail(mailbox):
account = mailbox.mail_domain.account
job = getattr(mailbox, "provisioning", None)
return (
not account.services_suspended
and account.retired_at is None
and (job is None or job.state == "configured")
)
def actor_can_open_webmail(actor, mailbox):
if not (
can_reveal_credentials(actor, CredentialKind.MAILBOX)
and mailbox_can_open_webmail(mailbox)
):
return False
customer = customer_for_user(actor)
return (
customer is None
or mailbox.mail_domain.account.customer_id == customer.pk
)
class RoundcubeLaunch(MailboxCredentialView):
http_method_names = ["post"]
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
response["Referrer-Policy"] = "origin"
return response
@sensitive_variables()
def post(self, request, *args, **kwargs):
if not roundcube_available(request):
raise Http404
mailbox = self.resource
if not actor_can_open_webmail(request.user, mailbox):
raise Http404
token = issue_signon_grant(
RoundcubeGrant,
request.user,
mailbox=mailbox,
address=mailbox.spec.address,
)
return render(
request,
"hosting/service_signon.html",
{
"destination": settings.ROUNDCUBE_URL + "/",
"product": "Roundcube",
"resource": mailbox.spec.address,
"ticket_field": "_coulobre_ticket",
"ticket": token,
"account": self.account,
},
)
@csrf_exempt
@require_POST
@never_cache
@sensitive_post_parameters("ticket")
@sensitive_variables()
def redeem_roundcube(request):
if not roundcube_available(request):
raise Http404
token = bridge_ticket(request, settings.ROUNDCUBE_BRIDGE_KEY)
grant = consume_signon_grant(
RoundcubeGrant,
token,
"mailbox__mail_domain__account",
"mailbox__provisioning",
)
if grant is None or not actor_can_open_webmail(grant.actor, grant.mailbox):
raise Http404
mailbox = grant.mailbox
spec = mailbox.spec
if grant.address != spec.address:
raise Http404
audit = ServiceCredentialAccess.objects.create(
actor=grant.actor,
actor_username=grant.actor.get_username(),
hosting_account_id=mailbox.mail_domain.account_id,
kind=CredentialKind.MAILBOX,
resource=spec.address,
method=ServiceCredentialAccess.Method.WEBMAIL,
outcome=CredentialOutcome.REQUESTED,
)
try:
credentials = fetch_service_credentials(spec)
except (OSError, ValueError):
record_outcome(audit, CredentialOutcome.UNAVAILABLE)
return JsonResponse(
{"error": "Mailbox login unavailable."}, status=503
)
current = (
HostingMailbox.objects.select_related(
"mail_domain__account", "provisioning"
)
.filter(pk=mailbox.pk)
.first()
)
actor = get_user_model().objects.filter(pk=grant.actor_id).first()
if (
current is None
or actor is None
or current.spec != spec
or not actor_can_open_webmail(actor, current)
):
record_outcome(audit, CredentialOutcome.UNAVAILABLE)
raise Http404
record_outcome(audit, CredentialOutcome.REVEALED)
response = JsonResponse(credentials)
response["Referrer-Policy"] = "no-referrer"
return response
def record_outcome(audit, outcome):
audit.outcome = outcome
audit.save(update_fields=["outcome"])
+57
View File
@@ -0,0 +1,57 @@
import hashlib
import hmac
import re
import secrets
from datetime import timedelta
from django.db import transaction
from django.http import Http404
from django.utils import timezone
from django.views.decorators.debug import sensitive_variables
GRANT_LIFETIME = timedelta(seconds=45)
TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}")
@sensitive_variables()
def issue_signon_grant(model, actor, **selection):
now = timezone.now()
model.objects.filter(expires_at__lte=now).delete()
token = secrets.token_urlsafe(32)
model.objects.create(
token_digest=token_digest(token),
actor=actor,
expires_at=now + GRANT_LIFETIME,
**selection,
)
return token
@sensitive_variables()
def token_digest(token):
return hashlib.sha256(token.encode("ascii")).hexdigest()
@transaction.atomic
@sensitive_variables()
def consume_signon_grant(model, token, *related):
now = timezone.now()
current = model.objects.filter(pk=token_digest(token))
if not current.filter(expires_at__gt=now, redeemed_at__isnull=True).update(
redeemed_at=now
):
return None
return current.select_related("actor", *related).first()
@sensitive_variables()
def bridge_ticket(request, expected_key):
key = request.headers.get("X-Coulobre-Bridge-Key", "")
if not expected_key or not hmac.compare_digest(
key.encode("utf-8"), expected_key.encode("utf-8")
):
raise Http404
ticket = request.POST.get("ticket", "")
if not TOKEN_PATTERN.fullmatch(ticket):
raise Http404
return ticket
@@ -1,3 +0,0 @@
"use strict";
document.getElementById("phpmyadmin-launch").submit();
@@ -0,0 +1,3 @@
"use strict";
document.getElementById("service-signon").submit();
@@ -209,6 +209,12 @@
<tr>
<td class="domain">
{{ mailbox }}
{% if mailbox.pk in webmail_mailbox_ids %}
<form method="post" action="{% url 'panel:roundcube_launch' mailbox.pk %}">
{% csrf_token %}
<button class="button secondary" type="submit" aria-label="Open webmail for {{ mailbox }}">Open webmail</button>
</form>
{% endif %}
{% if show_mailbox_credentials %}
<div><a class="record-link" href="{% url 'panel:mailbox_credentials' mailbox.pk %}" aria-label="Connection details for {{ mailbox }}">Connection details</a></div>
{% endif %}
@@ -1,21 +0,0 @@
{% extends "hosting/base.html" %}
{% load static %}
{% block title %}Opening phpMyAdmin · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Opening phpMyAdmin</h1>
<p class="heading-meta domain">{{ database }}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" action="{{ destination }}" id="phpmyadmin-launch" class="editor">
<input type="hidden" name="ticket" value="{{ ticket }}">
<div class="form-actions">
<button class="button primary" type="submit">Continue to phpMyAdmin</button>
</div>
</form>
</section>
<script src="{% static 'hosting/phpmyadmin-launch.js' %}" defer></script>
{% endblock %}
@@ -0,0 +1,21 @@
{% extends "hosting/base.html" %}
{% load static %}
{% block title %}Opening {{ product }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Opening {{ product }}</h1>
<p class="heading-meta domain">{{ resource }}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" action="{{ destination }}" id="service-signon" class="editor">
<input type="hidden" name="{{ ticket_field }}" value="{{ ticket }}">
<div class="form-actions">
<button class="button primary" type="submit">Continue to {{ product }}</button>
</div>
</form>
</section>
<script src="{% static 'hosting/service-signon.js' %}" defer></script>
{% endblock %}
+200
View File
@@ -0,0 +1,200 @@
import re
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from .models import (
Customer,
HostingAccount,
HostingMailbox,
HostingMailDomain,
MailboxProvisioning,
PhpMyAdminGrant,
RoundcubeGrant,
ServiceCredentialAccess,
)
from .signon import issue_signon_grant
BRIDGE_KEY = "roundcube-fixture-bridge-key-with-separate-access"
MAIL_PASSWORD = "fixture-mailbox-password"
@override_settings(
DEBUG=False,
LOCAL_MAILBOX_CREDENTIALS=False,
REMOTE_MAILBOX_CREDENTIALS=True,
ROUNDCUBE_URL="https://webmail.example.org",
ROUNDCUBE_BRIDGE_KEY=BRIDGE_KEY,
)
class RoundcubeSignOnTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.user = users.create_user("tenant")
cls.other = users.create_user("other")
cls.customer = Customer.objects.create(user=cls.user)
cls.other_customer = Customer.objects.create(user=cls.other)
cls.account = HostingAccount.objects.create(
name="Own site",
primary_domain="site.example",
customer=cls.customer,
)
domain = HostingMailDomain.objects.create(
account=cls.account, domain=cls.account.primary_domain
)
cls.first = HostingMailbox.objects.create(
mail_domain=domain, local_part="first", quota_mib=10
)
cls.second = HostingMailbox.objects.create(
mail_domain=domain, local_part="second"
)
def setUp(self):
self.client.force_login(self.user)
self.bridge = reverse("panel:roundcube_redeem")
def launch_url(self, mailbox):
return reverse("panel:roundcube_launch", args=[mailbox.pk])
def issue(self, mailbox):
response = self.client.post(self.launch_url(mailbox), secure=True)
self.assertContains(response, mailbox.spec.address)
self.assertContains(response, 'action="https://webmail.example.org/"')
self.assertNotContains(response, MAIL_PASSWORD)
self.assertIn("no-store", response.headers["Cache-Control"])
self.assertEqual(response.headers["Referrer-Policy"], "origin")
ticket = (
re.search(
rb'name="_coulobre_ticket" value="([A-Za-z0-9_-]{43})"',
response.content,
)
.group(1)
.decode("ascii")
)
return ticket
def redeem(self, ticket, key=BRIDGE_KEY):
return Client().post(
self.bridge,
{"ticket": ticket},
secure=True,
headers={"X-Coulobre-Bridge-Key": key},
)
def test_each_launch_redeems_only_its_selected_mailbox(self):
index = self.client.get(self.account.get_absolute_url(), secure=True)
self.assertContains(index, ">Open webmail</button>", count=2)
first, second = self.issue(self.first), self.issue(self.second)
self.assertFalse(
RoundcubeGrant.objects.filter(
token_digest__in=[first, second]
).exists()
)
with patch(
"coulobre.hosting.roundcube.fetch_service_credentials",
side_effect=lambda spec: {
"user": spec.address,
"password": MAIL_PASSWORD,
},
) as node:
for ticket, mailbox in (
(first, self.first),
(second, self.second),
):
response = self.redeem(ticket)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.json(),
{"user": mailbox.spec.address, "password": MAIL_PASSWORD},
)
self.assertIn("no-store", response.headers["Cache-Control"])
self.assertEqual(self.redeem(ticket).status_code, 404)
self.assertEqual(
[call.args[0] for call in node.call_args_list],
[self.first.spec, self.second.spec],
)
audits = ServiceCredentialAccess.objects.filter(method="webmail")
self.assertEqual(
set(audits.values_list("resource", flat=True)),
{self.first.spec.address, self.second.spec.address},
)
self.assertNotIn(MAIL_PASSWORD, str(list(audits.values())))
def test_expiry_key_and_product_boundaries(self):
ticket = self.issue(self.first)
self.assertEqual(self.redeem(ticket, "wrong key").status_code, 404)
self.assertIsNone(RoundcubeGrant.objects.get().redeemed_at)
RoundcubeGrant.objects.update(expires_at=timezone.now())
self.assertEqual(self.redeem(ticket).status_code, 404)
database = self.account.databases.create(suffix="app")
database_ticket = issue_signon_grant(
PhpMyAdminGrant, self.user, database=database
)
self.assertEqual(self.redeem(database_ticket).status_code, 404)
self.assertIsNone(PhpMyAdminGrant.objects.get().redeemed_at)
def test_another_tenant_cannot_launch_and_old_grants_lose_access(self):
ticket = self.issue(self.first)
self.client.force_login(self.other)
self.assertEqual(
self.client.post(
self.launch_url(self.first), secure=True
).status_code,
404,
)
HostingAccount.objects.filter(pk=self.account.pk).update(
customer=self.other_customer
)
with patch(
"coulobre.hosting.roundcube.fetch_service_credentials"
) as node:
self.assertEqual(self.redeem(ticket).status_code, 404)
node.assert_not_called()
def test_suspension_blocks_an_issued_ticket(self):
ticket = self.issue(self.first)
HostingAccount.objects.filter(pk=self.account.pk).update(
services_suspended=True
)
self.assertNotContains(
self.client.get(self.account.get_absolute_url(), secure=True),
"Open webmail",
)
self.assertEqual(self.redeem(ticket).status_code, 404)
def test_an_unfinished_mailbox_request_cannot_launch(self):
MailboxProvisioning.objects.create(mailbox=self.first)
response = self.client.get(
self.account.get_absolute_url(), secure=True
)
self.assertContains(response, ">Open webmail</button>", count=1)
self.assertEqual(
self.client.post(
self.launch_url(self.first), secure=True
).status_code,
404,
)
def test_requires_post_and_csrf(self):
url = self.launch_url(self.first)
self.assertEqual(self.client.get(url, secure=True).status_code, 405)
client = Client(enforce_csrf_checks=True)
client.force_login(self.user)
self.assertEqual(client.post(url, secure=True).status_code, 403)
self.assertFalse(RoundcubeGrant.objects.exists())
@override_settings(ROUNDCUBE_URL="")
def test_opt_in_is_required(self):
self.assertNotContains(
self.client.get(self.account.get_absolute_url(), secure=True),
"Open webmail",
)
self.assertEqual(
self.client.post(
self.launch_url(self.first), secure=True
).status_code,
404,
)
@@ -1,6 +1,7 @@
import json
import subprocess
from datetime import timedelta
from io import StringIO
from unittest.mock import patch
from django.contrib.auth import get_user_model
@@ -16,6 +17,7 @@ from coulobre.service_health import (
check_remote,
check_unit,
load_health_targets,
main,
)
from .models import Customer, Reseller, ServiceHealth
@@ -99,6 +101,37 @@ class ServiceHealthProbeTests(SimpleTestCase):
self.assertIn("StrictHostKeyChecking=yes", command)
self.assertEqual(command[-2:], ("--", "mail-02"))
def test_spam_filter_units_can_be_checked_locally_and_remotely(self):
filters = ("spamd", "spamass-milter")
self.assertEqual(
load_health_targets(
'{"panel":{"local":["spamd","spamass-milter"]},'
'"mail":{"ssh":["spamd","spamass-milter"]}}'
),
(
HealthTarget("panel", "local", filters),
HealthTarget("mail", "ssh", filters),
),
)
output = StringIO()
with (
patch("sys.stdout", output),
patch(
"coulobre.service_health.subprocess.run",
return_value=subprocess.CompletedProcess(
(), 0, b"LoadState=loaded\nActiveState=active\n"
),
) as run,
):
self.assertEqual(main(), 0)
units = {call.args[0][-1] for call in run.call_args_list}
self.assertTrue({"spamd.service", "spamass-milter.service"} <= units)
report = json.loads(output.getvalue())
self.assertEqual(
{name: report["services"][name] for name in filters},
dict.fromkeys(filters, "active"),
)
@override_settings(SERVICE_HEALTH_TARGETS=TARGETS)
class ServiceHealthPanelTests(TestCase):
+7
View File
@@ -13,6 +13,7 @@ from .reseller_views import (
ResellerList,
)
from .retirement_views import RetirementList, RetirementView
from .roundcube import RoundcubeLaunch, redeem_roundcube
app_name = "panel"
@@ -165,6 +166,12 @@ urlpatterns = [
name="phpmyadmin_launch",
),
path("_bridge/phpmyadmin/", redeem_phpmyadmin, name="phpmyadmin_redeem"),
path(
"mailboxes/<int:pk>/webmail/",
RoundcubeLaunch.as_view(),
name="roundcube_launch",
),
path("_bridge/roundcube/", redeem_roundcube, name="roundcube_redeem"),
path(
"databases/<int:pk>/credentials/",
DatabaseCredentialView.as_view(),
+15
View File
@@ -110,6 +110,7 @@ from .resource_requests import (
require_open_account,
)
from .retirement_views import RETIRE_ACCOUNTS
from .roundcube import mailbox_can_open_webmail, roundcube_available
from .service_changes import request_service_change
from .service_credentials import (
CredentialKind,
@@ -490,6 +491,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["show_phpmyadmin"] = context[
"show_database_credentials"
] and phpmyadmin_available(self.request)
context["show_webmail"] = context[
"show_mailbox_credentials"
] and roundcube_available(self.request)
if tenant or user.has_perm(VIEW_DATABASES):
databases = self.object.databases.all()
if not tenant and user.has_perms(PROVISION_DATABASE):
@@ -525,6 +529,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["change_mailbox_quota"] = user.has_perms(
CHANGE_MAILBOX_QUOTA
)
if context.get("show_webmail"):
mailboxes = list(
mailboxes.select_related(
"mail_domain__account", "provisioning"
)
)
context["webmail_mailbox_ids"] = {
mailbox.pk
for mailbox in mailboxes
if mailbox_can_open_webmail(mailbox)
}
context["mailboxes"] = mailboxes
return context
+5 -2
View File
@@ -15,8 +15,10 @@ SERVICES = {
"bind9": ("BIND9", "named.service"),
"postfix": ("Postfix", "postfix.service"),
"dovecot": ("Dovecot", "dovecot.service"),
"spamd": ("SpamAssassin", "spamd.service"),
"spamass-milter": ("SpamAssassin milter", "spamass-milter.service"),
}
REMOTE_SERVICES = ("bind9", "postfix", "dovecot")
REMOTE_SERVICES = ("bind9", "postfix", "dovecot", "spamd", "spamass-milter")
REMOTE_VERSION = 1
SSH_CONFIG = "/etc/coulobre-health/ssh_config"
NODE_NAME = re.compile(r"[a-z][a-z0-9-]{0,62}")
@@ -172,7 +174,8 @@ def check_remote(target):
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
timeout=15,
# Allow for SSH setup and sequential unit checks.
timeout=22,
check=True,
)
except (OSError, subprocess.SubprocessError):
+22
View File
@@ -1,4 +1,5 @@
import os
import re
from pathlib import Path
from urllib.parse import urlsplit
@@ -175,6 +176,27 @@ if PHPMYADMIN_URL:
"Set a random phpMyAdmin bridge key of at least 32 characters."
)
ROUNDCUBE_URL = os.environ.get("COULOBRE_ROUNDCUBE_URL", "").rstrip("/")
ROUNDCUBE_BRIDGE_KEY = os.environ.get("COULOBRE_ROUNDCUBE_BRIDGE_KEY", "")
if ROUNDCUBE_URL:
roundcube = urlsplit(ROUNDCUBE_URL)
if (
roundcube.scheme != "https"
or not roundcube.hostname
or roundcube.username is not None
or roundcube.query
or roundcube.fragment
or any(character.isspace() for character in ROUNDCUBE_URL)
):
raise ImproperlyConfigured("Set an HTTPS Roundcube base URL.")
if (
re.fullmatch(r"[A-Za-z0-9_-]{32,128}", ROUNDCUBE_BRIDGE_KEY) is None
or ROUNDCUBE_BRIDGE_KEY == PHPMYADMIN_BRIDGE_KEY
):
raise ImproperlyConfigured(
"Set a dedicated random Roundcube bridge key."
)
LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
LOCAL_ACCOUNT_BACKUP_MAIL = (
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"