Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d076f111b6 | ||
|
|
ef95ed9521 | ||
|
|
004a8b4d81 | ||
|
|
bb617a99ee | ||
|
|
7d380f093d | ||
|
|
de9a560f6a | ||
|
|
3afdbb08ad | ||
|
|
653d365645 | ||
|
|
07b26838c9 |
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# Include in dovecot.conf or a loaded conf.d file.
|
||||
auth_mechanisms = plain login
|
||||
service auth {
|
||||
unix_listener /var/spool/postfix/private/auth {
|
||||
mode = 0660
|
||||
user = postfix
|
||||
group = postfix
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,15 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
||||
# COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1
|
||||
# COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1
|
||||
# COULOBRE_MAIL_IMAP_HOST=mail.example.org
|
||||
# COULOBRE_MAIL_MX_HOST=mx.example.org
|
||||
# COULOBRE_MAIL_DNS_RESOLVERS=
|
||||
# COULOBRE_MAIL_SENDING_IPS=
|
||||
# COULOBRE_MAIL_MX_IPS=
|
||||
# COULOBRE_MANAGE_MAIL_DNS=1
|
||||
# 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
|
||||
|
||||
@@ -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>
|
||||
@@ -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';
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
@@ -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,15 @@
|
||||
# /etc/rspamd/override.d/dkim_signing.conf
|
||||
enabled = true;
|
||||
selector = "coulobre";
|
||||
path = "/etc/rspamd/coulobre-dkim/$domain.$selector.key";
|
||||
use_domain = "header";
|
||||
use_esld = false;
|
||||
try_fallback = true;
|
||||
sign_authenticated = true;
|
||||
sign_local = false;
|
||||
sign_inbound = false;
|
||||
allow_envfrom_empty = false;
|
||||
allow_hdrfrom_multiple = false;
|
||||
allow_hdrfrom_mismatch = false;
|
||||
allow_hdrfrom_mismatch_local = false;
|
||||
allow_username_mismatch = false;
|
||||
@@ -0,0 +1,10 @@
|
||||
# Merge these options into the existing authenticated submission service.
|
||||
# Leave the public SMTP service and its inbound milters in place.
|
||||
submission inet n - y - - smtpd
|
||||
-o smtpd_tls_security_level=encrypt
|
||||
-o smtpd_tls_auth_only=yes
|
||||
-o smtpd_sasl_auth_enable=yes
|
||||
-o smtpd_sasl_type=dovecot
|
||||
-o smtpd_sasl_path=private/auth
|
||||
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
|
||||
-o { smtpd_milters = { unix:rspamd/coulobre.sock, default_action=tempfail } }
|
||||
@@ -0,0 +1,8 @@
|
||||
# /etc/rspamd/local.d/settings.conf
|
||||
coulobre_signing {
|
||||
authenticated = true;
|
||||
apply {
|
||||
symbols_enabled = ["DKIM_SIGNED"];
|
||||
flags = ["skip_process"];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# /etc/rspamd/override.d/worker-normal.inc and worker-controller.inc
|
||||
enabled = false;
|
||||
@@ -0,0 +1,7 @@
|
||||
# /etc/rspamd/override.d/worker-proxy.inc
|
||||
bind_socket = "/var/spool/postfix/rspamd/coulobre.sock mode=0600 owner=postfix";
|
||||
milter = true;
|
||||
upstream "local" {
|
||||
default = true;
|
||||
self_scan = true;
|
||||
}
|
||||
@@ -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"
|
||||
+263
-3
@@ -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,192 @@ 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)
|
||||
|
||||
## Check and provision mail DNS
|
||||
|
||||
Open **Check mail DNS** under **Mail domains**. The check reads MX and
|
||||
its address records, SPF, DMARC, DKIM public keys, the MTA-STS and TLS-RPT
|
||||
DNS records, and reverse DNS for configured sending addresses. Use the
|
||||
DKIM selector supplied by the signer or the `s=` value from a sent
|
||||
message's `DKIM-Signature` header. Coulobre fills in selectors it knows.
|
||||
|
||||
The panel uses its system resolver by default. For internet-facing mail,
|
||||
set `COULOBRE_MAIL_DNS_RESOLVERS` to a comma-separated list of up to three
|
||||
trusted recursive resolvers with a public DNS view. An authoritative-only
|
||||
BIND instance serves zones and may not answer queries for other domains.
|
||||
Results describe the returned records and their basic validity. Verify
|
||||
SPF evaluation, DKIM signatures, DMARC alignment and mail delivery with a
|
||||
message sent to an independent mailbox. The MTA-STS check reads its DNS
|
||||
policy ID. Checking the HTTPS policy is a separate step. The DKIM check
|
||||
compares the managed selector with the public key received from the mail
|
||||
node.
|
||||
|
||||
### Set up signing on a Coulobre mail node
|
||||
|
||||
Install the distribution's `rspamd` package on the mail node, including
|
||||
when the node is separate from the panel. This example dedicates Rspamd
|
||||
to signing authenticated Postfix submission. It uses a private Postfix
|
||||
socket and disables Rspamd's normal and controller listeners. The
|
||||
mail host can still use [SpamAssassin for incoming SMTP](#filter-incoming-mail-with-spamassassin).
|
||||
[Rspamd signing options](https://docs.rspamd.com/modules/dkim_signing/)
|
||||
|
||||
```sh
|
||||
sudo apt install rspamd
|
||||
sudo install -d -o root -g _rspamd -m 0750 /etc/rspamd/coulobre-dkim
|
||||
sudo install -d -o root -g postfix -m 0750 /var/spool/postfix/rspamd
|
||||
sudo install -m 0644 deploy/rspamd/dkim_signing.conf.example \
|
||||
/etc/rspamd/override.d/dkim_signing.conf
|
||||
sudo install -m 0644 deploy/rspamd/worker-proxy.inc.example \
|
||||
/etc/rspamd/override.d/worker-proxy.inc
|
||||
for worker in normal controller; do
|
||||
sudo install -m 0644 deploy/rspamd/worker-disabled.inc.example \
|
||||
"/etc/rspamd/override.d/worker-$worker.inc"
|
||||
done
|
||||
sudo install -m 0644 deploy/rspamd/settings.conf.example \
|
||||
/etc/rspamd/local.d/settings.conf
|
||||
sudo rspamadm configtest
|
||||
sudo systemctl enable rspamd.service
|
||||
sudo systemctl restart rspamd.service
|
||||
```
|
||||
|
||||
Configure TLS for Postfix and include
|
||||
`deploy/dovecot/submission-auth.conf.example` in the Dovecot configuration
|
||||
to provide the SASL socket. Use full email addresses for authentication.
|
||||
Merge `deploy/rspamd/postfix-submission.cf.example` into the
|
||||
`submission` service in `/etc/postfix/master.cf`. Use the signing socket
|
||||
only from authenticated submission. Keep any inbound milters on the
|
||||
public SMTP service. Rspamd signs when the authenticated domain,
|
||||
envelope sender domain, and header sender domain agree.
|
||||
[Postfix SASL setup](https://www.postfix.org/SASL_README.html)
|
||||
|
||||
```sh
|
||||
sudo systemctl restart dovecot.service
|
||||
sudo postfix check
|
||||
sudo postfix reload
|
||||
```
|
||||
|
||||
Configure the panel and mailbox worker in `/etc/coulobre/panel.env`.
|
||||
Set the inbound hostname separately from the sending addresses. Set
|
||||
`COULOBRE_MAIL_MX_IPS` when Coulobre should also create address records for
|
||||
an MX hostname inside the managed zone. Ensure an MX hostname outside
|
||||
the zone already has public addresses at its DNS provider. Replace the
|
||||
documentation addresses below with the real public addresses.
|
||||
|
||||
```ini
|
||||
COULOBRE_MANAGE_MAIL_DNS=1
|
||||
COULOBRE_MAIL_MX_HOST=mx.example.net
|
||||
COULOBRE_MAIL_MX_IPS=192.0.2.25
|
||||
COULOBRE_MAIL_SENDING_IPS=192.0.2.25,2001:db8::25
|
||||
```
|
||||
|
||||
Upgrade Coulobre on the panel and mail node, apply migrations, collect
|
||||
static files and restart the panel, workers and scheduler. Provisioning a
|
||||
mailbox creates or reuses a per-domain RSA DKIM key with selector
|
||||
`coulobre`. The signing key stays on the mail node. Include
|
||||
`/etc/rspamd/coulobre-dkim` in the operator's protected configuration
|
||||
backup. For an existing mailbox, an operator can run **Refresh mail DNS
|
||||
setup** on the domain's checker page.
|
||||
|
||||
### Publish records with Coulobre DNS
|
||||
|
||||
Enable the local or SSH-backed DNS publishing worker and select
|
||||
**Publish DNS for Coulobre mail automatically** in the zone's editor.
|
||||
Provision a mailbox or refresh its mail DNS setup. Coulobre adds the MX
|
||||
record, any needed in-zone addresses, an SPF policy for the configured
|
||||
sending IPs, a monitoring DMARC record, and the DKIM public key. It
|
||||
queues the revised zone through the configured DNS worker.
|
||||
|
||||
The job waits for a publishing request already in progress. Publish
|
||||
unpublished zone edits before applying a conflicting mail setup. Review
|
||||
existing MX or DKIM conflicts from the checker page. Coulobre preserves
|
||||
existing SPF and DMARC policies. When other systems also send for the
|
||||
domain, include them in SPF before asking receivers to enforce DMARC.
|
||||
Configure PTR with the provider that assigns the public sending IP.
|
||||
|
||||
### Publish records with third-party DNS
|
||||
|
||||
The checker shows the DNS zone and nameservers observed by the resolver.
|
||||
Open the DNS editor at the company hosting that zone. Use the registrar's
|
||||
editor when the registrar also runs its nameservers. Leave automatic
|
||||
publishing off for a zone hosted by a third party.
|
||||
|
||||
Copy the record names, values, and MX priorities from **Where to edit
|
||||
DNS**. Use the full record name or the relative name expected by the
|
||||
provider. Keep one SPF policy and merge all authorized senders into it.
|
||||
For a third-party signer, use its exact DKIM TXT or CNAME records. Publish
|
||||
the records and run the checker again after the old TTL has expired.
|
||||
|
||||
## 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 +1252,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 +1492,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.
|
||||
|
||||
@@ -12,6 +12,8 @@ license = "Apache-2.0"
|
||||
dependencies = [
|
||||
"Django>=5.2.8,<5.3",
|
||||
"celery>=5.6,<6",
|
||||
"cryptography>=45",
|
||||
"dnspython>=2.7,<3",
|
||||
"idna>=3,<4",
|
||||
]
|
||||
|
||||
|
||||
@@ -61,6 +61,14 @@ class DnsZoneForm(forms.Form):
|
||||
"special whitespace or enter an empty value."
|
||||
),
|
||||
)
|
||||
manage_mail_dns = forms.BooleanField(
|
||||
label="Publish DNS for Coulobre mail automatically",
|
||||
required=False,
|
||||
help_text=(
|
||||
"Use this when this zone is served by a local or remote "
|
||||
"Coulobre DNS node."
|
||||
),
|
||||
)
|
||||
|
||||
def __init__(self, *args, domain, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
|
||||
from coulobre.dns_node import DNS_REQUEST_LIMIT
|
||||
|
||||
@@ -26,6 +28,15 @@ def publish_for_account(account_id, zone_id, expected_serial):
|
||||
"This zone changed before publication. "
|
||||
"Reload the account and try again."
|
||||
)
|
||||
queue_zone_snapshot(zone)
|
||||
if settings.MANAGE_MAIL_DNS and zone.manage_mail_dns:
|
||||
account.mail_domains.exclude(dkim_record="").filter(
|
||||
Q(domain=zone.domain) | Q(domain__endswith=f".{zone.domain}")
|
||||
).update(dns_sync_requested=True)
|
||||
return zone
|
||||
|
||||
|
||||
def queue_zone_snapshot(zone):
|
||||
manifest = zone.spec.manifest()
|
||||
if len(encode_manifest(manifest)) > DNS_REQUEST_LIMIT:
|
||||
raise ValueError(
|
||||
@@ -40,4 +51,3 @@ def publish_for_account(account_id, zone_id, expected_serial):
|
||||
jobs.filter(pk=job.pk).exclude(serial=zone.serial, problem=""),
|
||||
**snapshot,
|
||||
)
|
||||
return zone
|
||||
@@ -20,6 +20,7 @@ PREVIEW_VIEWS = frozenset(
|
||||
"panel:account",
|
||||
"panel:database_create",
|
||||
"panel:mailbox_create",
|
||||
"panel:mail_dns_check",
|
||||
"panel:sftp_keys",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
from dataclasses import replace
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import transaction
|
||||
|
||||
from coulobre.dns_node import (
|
||||
MAX_SOA_SERIAL,
|
||||
AddressRecord,
|
||||
MxRecord,
|
||||
TxtRecord,
|
||||
)
|
||||
from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version
|
||||
|
||||
from .dns_publication import queue_zone_snapshot
|
||||
from .models import HostingDnsZone, HostingMailDomain, MailboxProvisioning
|
||||
from .resource_requests import lock_hosting_account, require_active_services
|
||||
|
||||
|
||||
class MailDnsPublicationPendingError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def domain_ancestors(domain):
|
||||
labels = domain.split(".")
|
||||
return [".".join(labels[index:]) for index in range(len(labels) - 1)]
|
||||
|
||||
|
||||
def closest_zone(queryset, domain):
|
||||
zones = queryset.filter(domain__in=domain_ancestors(domain))
|
||||
return max(zones, key=lambda zone: len(zone.domain), default=None)
|
||||
|
||||
|
||||
def mail_dns_proposal(domain, public_key):
|
||||
mx_host = settings.MAIL_MX_HOST
|
||||
addresses = tuple(
|
||||
AddressRecord(mx_host, address)
|
||||
for address in settings.MAIL_MX_IPS
|
||||
if mx_host
|
||||
)
|
||||
mx = (MxRecord(domain, 10, mx_host),) if mx_host else ()
|
||||
records = []
|
||||
if settings.MANAGE_MAIL_DNS:
|
||||
senders = " ".join(
|
||||
f"{'ip6' if ':' in address else 'ip4'}:{address}"
|
||||
for address in settings.MAIL_SENDING_IPS
|
||||
)
|
||||
records.append(TxtRecord(domain, f"v=spf1 {senders} ~all"))
|
||||
if len(f"_dmarc.{domain}") <= 253:
|
||||
records.append(TxtRecord(f"_dmarc.{domain}", "v=DMARC1; p=none"))
|
||||
if public_key:
|
||||
records.append(
|
||||
TxtRecord(
|
||||
f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}", public_key
|
||||
)
|
||||
)
|
||||
return addresses, mx, tuple(records)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def sync_mail_dns(mail_domain, *, public_key=None):
|
||||
account = lock_hosting_account(mail_domain.account_id, customer_id=None)
|
||||
current = HostingMailDomain.objects.filter(
|
||||
pk=mail_domain.pk, account=account
|
||||
).first()
|
||||
if current is None or account.retired_at is not None:
|
||||
return
|
||||
if public_key is not None:
|
||||
current.dkim_record = public_key
|
||||
current.dns_sync_requested = True
|
||||
current.save(update_fields=["dkim_record", "dns_sync_requested"])
|
||||
if not current.dns_sync_requested or account.services_suspended:
|
||||
return
|
||||
zone = None
|
||||
if settings.LOCAL_DNS_PUBLISHING:
|
||||
zone = closest_zone(HostingDnsZone.objects.all(), current.domain)
|
||||
problem = ""
|
||||
if (
|
||||
zone is not None
|
||||
and zone.account_id == account.pk
|
||||
and zone.manage_mail_dns
|
||||
):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
zone = HostingDnsZone.objects.select_for_update().get(
|
||||
pk=zone.pk, account=account
|
||||
)
|
||||
problem = publish_mail_records(
|
||||
zone, current.domain, current.dkim_record
|
||||
)
|
||||
except MailDnsPublicationPendingError:
|
||||
return
|
||||
except ValueError as error:
|
||||
problem = str(error)
|
||||
current.dns_sync_requested = False
|
||||
current.dns_setup_problem = problem
|
||||
current.save(update_fields=["dns_sync_requested", "dns_setup_problem"])
|
||||
|
||||
|
||||
def publish_mail_records(zone, domain, public_key):
|
||||
addresses, mx, txt = mail_dns_proposal(domain, public_key)
|
||||
spec = zone.spec
|
||||
|
||||
current_mx = [
|
||||
record for record in spec.mx_records if record.name == domain
|
||||
]
|
||||
if current_mx and all(
|
||||
record.exchange != mx[0].exchange for record in current_mx
|
||||
):
|
||||
raise ValueError(
|
||||
"Review the current MX targets before publishing mail DNS."
|
||||
)
|
||||
|
||||
target = mx[0].exchange
|
||||
current_addresses = {
|
||||
record.address for record in spec.addresses if record.name == target
|
||||
}
|
||||
managed_target = target == zone.domain or target.endswith(
|
||||
f".{zone.domain}"
|
||||
)
|
||||
additions = ()
|
||||
if managed_target:
|
||||
desired = {record.address for record in addresses}
|
||||
if current_addresses and desired and current_addresses - desired:
|
||||
raise ValueError("Review the existing addresses of the MX target.")
|
||||
additions = tuple(
|
||||
record
|
||||
for record in addresses
|
||||
if record.address not in current_addresses
|
||||
)
|
||||
if not (current_addresses or additions):
|
||||
raise ValueError(
|
||||
"Set addresses for the MX target inside this zone."
|
||||
)
|
||||
|
||||
existing = spec.txt_records
|
||||
new_txt = []
|
||||
problem = ""
|
||||
for record in txt:
|
||||
version = record.text.split(" ")[0].rstrip(";")
|
||||
at_owner = tuple(item for item in existing if item.name == record.name)
|
||||
if version == "v=DKIM1":
|
||||
if at_owner and at_owner != (record,):
|
||||
raise ValueError(
|
||||
"The Coulobre DKIM selector already has a record."
|
||||
)
|
||||
else:
|
||||
at_owner = tuple(
|
||||
item
|
||||
for item in at_owner
|
||||
if matches_version(item.text, version)
|
||||
)
|
||||
if len(at_owner) > 1:
|
||||
raise ValueError(
|
||||
"Resolve duplicate SPF or DMARC records before publishing."
|
||||
)
|
||||
if not at_owner:
|
||||
new_txt.append(record)
|
||||
elif version == "v=spf1" and record != at_owner[0]:
|
||||
problem = "Existing SPF policy kept. Verify the sending IPs."
|
||||
|
||||
publication = getattr(zone, "publication", None)
|
||||
if publication and publication.serial != zone.serial:
|
||||
raise ValueError(
|
||||
"Publish the saved zone revision before updating mail DNS."
|
||||
)
|
||||
changed = bool(additions or not current_mx or new_txt)
|
||||
if publication and publication.finished_at is None:
|
||||
if changed:
|
||||
raise MailDnsPublicationPendingError
|
||||
return problem
|
||||
|
||||
if changed:
|
||||
spec = replace(
|
||||
spec,
|
||||
serial=(spec.serial + 1) % (MAX_SOA_SERIAL + 1),
|
||||
addresses=spec.addresses + additions,
|
||||
mx_records=spec.mx_records + (mx if not current_mx else ()),
|
||||
txt_records=spec.txt_records + tuple(new_txt),
|
||||
)
|
||||
manifest = spec.manifest()
|
||||
zone.serial = spec.serial
|
||||
zone.addresses = manifest["addresses"]
|
||||
zone.mx_records = manifest["mx_records"]
|
||||
zone.txt_records = manifest["txt_records"]
|
||||
zone.save(
|
||||
update_fields=["serial", "addresses", "mx_records", "txt_records"]
|
||||
)
|
||||
if changed or publication is None or publication.problem:
|
||||
queue_zone_snapshot(zone)
|
||||
return problem
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def queue_mail_dns_setup(mail_domain):
|
||||
account = lock_hosting_account(mail_domain.account_id, customer_id=None)
|
||||
require_active_services(account)
|
||||
jobs = MailboxProvisioning.objects.filter(
|
||||
mailbox__mail_domain=mail_domain, finished_at__isnull=False, problem=""
|
||||
)
|
||||
job = jobs.select_for_update().order_by("pk").first()
|
||||
if job is None:
|
||||
raise ValidationError("Provision a mailbox for this domain first.")
|
||||
MailboxProvisioning.objects.requeue(
|
||||
jobs.filter(pk=job.pk), quota_update=False
|
||||
)
|
||||
@@ -0,0 +1,274 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.http import Http404, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views import View
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import FormView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.mail_dns import (
|
||||
MANAGED_DKIM_SELECTOR,
|
||||
MAX_SELECTORS,
|
||||
SELECTOR,
|
||||
matches_version,
|
||||
run_mail_dns,
|
||||
)
|
||||
|
||||
from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant
|
||||
from .mail_dns_setup import (
|
||||
closest_zone,
|
||||
mail_dns_proposal,
|
||||
queue_mail_dns_setup,
|
||||
)
|
||||
from .models import HostingMailDomain
|
||||
from .views import (
|
||||
PROVISION_MAILBOX,
|
||||
VIEW_ACCOUNTS,
|
||||
VIEW_DNS_ZONES,
|
||||
VIEW_MAILBOXES,
|
||||
)
|
||||
|
||||
|
||||
class MailDnsForm(forms.Form):
|
||||
selectors = forms.CharField(
|
||||
label="DKIM selectors",
|
||||
required=False,
|
||||
max_length=1024,
|
||||
help_text=(
|
||||
"Enter up to four selectors, separated by commas or spaces. "
|
||||
"Use the selector from your mail provider or the s= value in "
|
||||
"the DKIM-Signature header of a sent message."
|
||||
),
|
||||
widget=forms.TextInput(
|
||||
attrs={"autocomplete": "off", "spellcheck": "false"}
|
||||
),
|
||||
)
|
||||
|
||||
def __init__(self, *args, domain, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
def clean_selectors(self):
|
||||
selectors = tuple(
|
||||
dict.fromkeys(
|
||||
selector.lower()
|
||||
for selector in re.split(
|
||||
r"[\s,]+", self.cleaned_data["selectors"]
|
||||
)
|
||||
if selector
|
||||
)
|
||||
)
|
||||
if len(selectors) > MAX_SELECTORS:
|
||||
raise forms.ValidationError("Enter up to four DKIM selectors.")
|
||||
if any(
|
||||
not selector_fits(selector, self.domain) for selector in selectors
|
||||
):
|
||||
raise forms.ValidationError(
|
||||
"Enter selector names only, using letters, digits, hyphens "
|
||||
"and periods between labels."
|
||||
)
|
||||
return selectors
|
||||
|
||||
|
||||
def selector_fits(selector, domain):
|
||||
return bool(
|
||||
len(f"{selector}._domainkey.{domain}") <= 253
|
||||
and SELECTOR.fullmatch(selector)
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DnsEntry:
|
||||
name: str
|
||||
kind: str
|
||||
value: str
|
||||
priority: int | None = None
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class MailDnsCheckView(
|
||||
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView
|
||||
):
|
||||
queryset = HostingMailDomain.objects.select_related("account")
|
||||
customer_relation = "account__customer"
|
||||
reseller_relation = "account__reseller"
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES)
|
||||
template_name = "hosting/mail_dns_check.html"
|
||||
form_class = MailDnsForm
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.load_domain()
|
||||
return super().get(request, *args, **kwargs)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
self.load_domain()
|
||||
return super().post(request, *args, **kwargs)
|
||||
|
||||
def load_domain(self):
|
||||
self.object = self.get_object()
|
||||
self.domain = self.object.domain
|
||||
self.zone = None
|
||||
self.zone_txt = ()
|
||||
self.zone_mx = ()
|
||||
self.zone_addresses = ()
|
||||
if is_tenant(self.request.user) or self.request.user.has_perm(
|
||||
VIEW_DNS_ZONES
|
||||
):
|
||||
self.zone = closest_zone(
|
||||
self.object.account.dns_zones.all(), self.domain
|
||||
)
|
||||
if self.zone:
|
||||
spec = self.zone.spec
|
||||
self.zone_txt = spec.txt_records
|
||||
self.zone_mx = spec.mx_records
|
||||
self.zone_addresses = spec.addresses
|
||||
|
||||
def get_initial(self):
|
||||
initial = super().get_initial()
|
||||
suffix = f"._domainkey.{self.domain}"
|
||||
selectors = dict.fromkeys(
|
||||
record.name.removesuffix(suffix)
|
||||
for record in self.zone_txt
|
||||
if record.name.endswith(suffix)
|
||||
and selector_fits(record.name.removesuffix(suffix), self.domain)
|
||||
)
|
||||
if self.object.dkim_record:
|
||||
selectors = {MANAGED_DKIM_SELECTOR: None} | selectors
|
||||
initial["selectors"] = ", ".join(tuple(selectors)[:MAX_SELECTORS])
|
||||
return initial
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return super().get_form_kwargs() | {"domain": self.domain}
|
||||
|
||||
def get_context_data(self, *, report=None, **kwargs):
|
||||
entries = self.guide_entries(report)
|
||||
return super().get_context_data(
|
||||
account=self.object.account,
|
||||
domain=self.domain,
|
||||
zone=self.zone,
|
||||
report=report,
|
||||
mail_domain=self.object,
|
||||
can_refresh=(
|
||||
settings.MANAGE_MAIL_DNS
|
||||
and settings.LOCAL_MAILBOX_PROVISIONING
|
||||
and not is_tenant(self.request.user)
|
||||
and self.request.user.has_perms(PROVISION_MAILBOX)
|
||||
and self.object.mailboxes.filter(
|
||||
provisioning__finished_at__isnull=False,
|
||||
provisioning__problem="",
|
||||
).exists()
|
||||
),
|
||||
zone_matches=bool(
|
||||
report
|
||||
and self.zone
|
||||
and report.zone == self.zone.domain
|
||||
and set(report.nameservers)
|
||||
== {host + "." for host in self.zone.nameservers}
|
||||
),
|
||||
entries=entries,
|
||||
sending_ips=settings.MAIL_SENDING_IPS,
|
||||
explicit_resolver=bool(settings.MAIL_DNS_RESOLVERS),
|
||||
dmarc_example=not any(
|
||||
entry.name == f"_dmarc.{self.domain}" for entry in entries
|
||||
)
|
||||
and not (
|
||||
report
|
||||
and any(
|
||||
check.label == "DMARC" and check.state != "missing"
|
||||
for check in report.checks
|
||||
)
|
||||
),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
report = run_mail_dns(
|
||||
self.domain,
|
||||
form.cleaned_data["selectors"],
|
||||
nameservers=settings.MAIL_DNS_RESOLVERS,
|
||||
expected_mx=settings.MAIL_MX_HOST,
|
||||
signing_record=self.object.dkim_record,
|
||||
sending_ips=settings.MAIL_SENDING_IPS,
|
||||
)
|
||||
return self.render_to_response(
|
||||
self.get_context_data(form=form, report=report)
|
||||
)
|
||||
|
||||
def guide_entries(self, report):
|
||||
addresses, mx, txt = mail_dns_proposal(
|
||||
self.domain, self.object.dkim_record
|
||||
)
|
||||
entries = [
|
||||
DnsEntry(record.name, "MX", record.exchange + ".", record.priority)
|
||||
for record in self.zone_mx
|
||||
if record.name == self.domain and record.exchange != "."
|
||||
]
|
||||
if not entries:
|
||||
entries.extend(
|
||||
DnsEntry(
|
||||
record.name, "MX", record.exchange + ".", record.priority
|
||||
)
|
||||
for record in mx
|
||||
)
|
||||
targets = {entry.value.removesuffix(".") for entry in entries}
|
||||
entries.extend(
|
||||
DnsEntry(record.name, record.record_type, record.address)
|
||||
for record in dict.fromkeys(self.zone_addresses + addresses)
|
||||
if record.name in targets
|
||||
)
|
||||
txt_owners = {
|
||||
self.domain: "v=spf1",
|
||||
f"_dmarc.{self.domain}": "v=DMARC1",
|
||||
f"_mta-sts.{self.domain}": "v=STSv1",
|
||||
f"_smtp._tls.{self.domain}": "v=TLSRPTv1",
|
||||
}
|
||||
own_key = f"{MANAGED_DKIM_SELECTOR}._domainkey.{self.domain}"
|
||||
entries.extend(
|
||||
DnsEntry(record.name, "TXT", record.text)
|
||||
for record in self.zone_txt
|
||||
if (
|
||||
record.name in txt_owners
|
||||
and matches_version(record.text, txt_owners[record.name])
|
||||
)
|
||||
or (
|
||||
record.name.endswith(f"._domainkey.{self.domain}")
|
||||
and (record.name != own_key or not self.object.dkim_record)
|
||||
)
|
||||
)
|
||||
saved_names = {entry.name for entry in entries if entry.kind == "TXT"}
|
||||
policy_names = {
|
||||
check.name
|
||||
for check in (report.checks if report else ())
|
||||
if check.label in {"SPF", "DMARC"} and check.state != "missing"
|
||||
}
|
||||
entries.extend(
|
||||
DnsEntry(record.name, "TXT", record.text)
|
||||
for record in txt
|
||||
if record.name not in saved_names | policy_names
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||
permission_required = PROVISION_MAILBOX
|
||||
|
||||
def post(self, request, pk):
|
||||
if not (
|
||||
settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING
|
||||
):
|
||||
raise Http404
|
||||
domain = get_object_or_404(HostingMailDomain, pk=pk)
|
||||
try:
|
||||
queue_mail_dns_setup(domain)
|
||||
except ValidationError as error:
|
||||
return HttpResponse(
|
||||
" ".join(error.messages), status=409, content_type="text/plain"
|
||||
)
|
||||
return redirect("panel:mail_dns_check", pk=pk)
|
||||
@@ -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,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,32 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-21 20:52
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0038_roundcube_signon"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="hostingdnszone",
|
||||
name="manage_mail_dns",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="dkim_record",
|
||||
field=models.CharField(blank=True, max_length=1024),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="dns_setup_problem",
|
||||
field=models.TextField(blank=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="hostingmaildomain",
|
||||
name="dns_sync_requested",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -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(
|
||||
@@ -471,6 +483,7 @@ class HostingDnsZone(models.Model):
|
||||
addresses = models.JSONField(default=list)
|
||||
mx_records = models.JSONField(default=list)
|
||||
txt_records = models.JSONField(default=list)
|
||||
manage_mail_dns = models.BooleanField(default=False)
|
||||
|
||||
class Meta:
|
||||
ordering = ("domain",)
|
||||
@@ -508,6 +521,9 @@ class HostingMailDomain(models.Model):
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="mail_domains"
|
||||
)
|
||||
domain = DomainNameField(max_length=253, unique=True)
|
||||
dkim_record = models.CharField(max_length=1024, blank=True)
|
||||
dns_setup_problem = models.TextField(blank=True)
|
||||
dns_sync_requested = models.BooleanField(default=False)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.domain)
|
||||
|
||||
@@ -11,7 +11,8 @@ from coulobre.account_restore_request import (
|
||||
RESTORE_SOCKET,
|
||||
RESTORE_TIMEOUT_SECONDS,
|
||||
)
|
||||
from coulobre.mail_node import MailboxQuotaUpdate
|
||||
from coulobre.mail_dns import dkim_key
|
||||
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
||||
from coulobre.php_pool_settings import PhpPoolSettings
|
||||
from coulobre.web_node import (
|
||||
MAX_STORAGE_BYTES,
|
||||
@@ -130,6 +131,24 @@ def provision_local_mailbox(mailbox):
|
||||
)
|
||||
|
||||
|
||||
def provision_signing_mailbox(mailbox):
|
||||
reply = apply_on_local_node(
|
||||
MailboxSigningRequest(mailbox),
|
||||
"/run/coulobre-mail-apply.sock",
|
||||
"mail node",
|
||||
"mailbox and signing key",
|
||||
)
|
||||
public = reply.get("dkim")
|
||||
if (
|
||||
not isinstance(public, str)
|
||||
or len(public) > 1024
|
||||
or not public.startswith("v=DKIM1; k=rsa; p=")
|
||||
or dkim_key(public)[0] != "ok"
|
||||
):
|
||||
raise ValueError("The mail node returned an invalid DKIM public key.")
|
||||
return public
|
||||
|
||||
|
||||
def update_local_mailbox_quota(mailbox):
|
||||
apply_on_local_node(
|
||||
MailboxQuotaUpdate(mailbox),
|
||||
|
||||
@@ -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
|
||||
):
|
||||
|
||||
@@ -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"])
|
||||
@@ -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
|
||||
+3
-3
@@ -1,13 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
const copyStatus = document.getElementById("credential-copy-status");
|
||||
const copyStatus = document.getElementById("copy-field-status");
|
||||
|
||||
for (const button of document.querySelectorAll("[data-copy-credential]")) {
|
||||
for (const button of document.querySelectorAll("[data-copy-field]")) {
|
||||
if (!navigator.clipboard) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const field = document.getElementById(button.dataset.copyCredential);
|
||||
const field = document.getElementById(button.dataset.copyField);
|
||||
button.hidden = false;
|
||||
button.addEventListener("click", async () => {
|
||||
if (!field.value) {
|
||||
@@ -647,3 +647,30 @@ dd {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.dns-answer {
|
||||
max-width: 38rem;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dns-answer p {
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
|
||||
.dns-instructions {
|
||||
padding: 1.2rem;
|
||||
}
|
||||
|
||||
.dns-instructions p,
|
||||
.dns-instructions ul {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.dns-instructions li + li {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.dns-instructions input {
|
||||
min-width: 12rem;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
document.getElementById("phpmyadmin-launch").submit();
|
||||
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
|
||||
document.getElementById("service-signon").submit();
|
||||
@@ -31,6 +31,7 @@ from .backup_restores import (
|
||||
enabled_component_restores,
|
||||
)
|
||||
from .backup_retention import plan_backup_expirations
|
||||
from .mail_dns_setup import sync_mail_dns
|
||||
from .models import (
|
||||
AccountBackupExpiration,
|
||||
AccountBackupJob,
|
||||
@@ -40,6 +41,7 @@ from .models import (
|
||||
ComponentRestoreJob,
|
||||
DatabaseProvisioning,
|
||||
DnsPublication,
|
||||
HostingMailDomain,
|
||||
MailboxProvisioning,
|
||||
SitePhpSettings,
|
||||
SiteSFTP,
|
||||
@@ -60,6 +62,7 @@ from .node_client import (
|
||||
measure_local_site_storage,
|
||||
provision_local_database,
|
||||
provision_local_mailbox,
|
||||
provision_signing_mailbox,
|
||||
publish_local_zone,
|
||||
restore_local_component,
|
||||
restore_local_website,
|
||||
@@ -192,6 +195,14 @@ def dispatch_database_provisioning():
|
||||
@shared_task
|
||||
def dispatch_dns_publications():
|
||||
if settings.LOCAL_DNS_PUBLISHING:
|
||||
if settings.MANAGE_MAIL_DNS:
|
||||
domains = HostingMailDomain.objects.filter(
|
||||
dns_sync_requested=True,
|
||||
account__services_suspended=False,
|
||||
account__retired_at__isnull=True,
|
||||
).order_by("pk")[:100]
|
||||
for mail_domain in domains:
|
||||
sync_mail_dns(mail_domain)
|
||||
dispatch_provisioning_jobs(
|
||||
DnsPublication, publish_dns_zone, DNS_PUBLISHING_QUEUE
|
||||
)
|
||||
@@ -609,6 +620,9 @@ def provision_mailbox(provisioning_id):
|
||||
def apply_mailbox_provisioning(provisioning):
|
||||
if provisioning.quota_update:
|
||||
update_local_mailbox_quota(provisioning.mailbox.spec)
|
||||
elif settings.MANAGE_MAIL_DNS:
|
||||
public_key = provision_signing_mailbox(provisioning.mailbox.spec)
|
||||
sync_mail_dns(provisioning.mailbox.mail_domain, public_key=public_key)
|
||||
else:
|
||||
provision_local_mailbox(provisioning.mailbox.spec)
|
||||
|
||||
|
||||
@@ -180,6 +180,26 @@
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if is_tenant or perms.hosting.view_hostingmailbox %}
|
||||
{% if mail_domains %}
|
||||
<section class="surface" aria-labelledby="mail-domains-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="mail-domains-heading">Mail domains</h2>
|
||||
</header>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Domain</th><th scope="col">DNS</th></tr></thead>
|
||||
<tbody>
|
||||
{% for domain in mail_domains %}
|
||||
<tr>
|
||||
<td class="domain">{{ domain }}</td>
|
||||
<td><a class="record-link" href="{% url 'panel:mail_dns_check' domain.pk %}" aria-label="Check mail DNS for {{ domain }}">Check mail DNS</a></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="surface" aria-labelledby="mailboxes-heading">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
@@ -209,6 +229,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 %}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<div class="form-actions">
|
||||
<input id="{{ key }}" type="text" aria-label="{{ label }}" readonly autocomplete="off" spellcheck="false" value="{{ value }}">
|
||||
<button class="button secondary" type="button" hidden data-copy-field="{{ key }}">Copy {{ label }}</button>
|
||||
</div>
|
||||
@@ -0,0 +1,140 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% load static %}
|
||||
{% block title %}Mail DNS check · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Mail DNS check</h1>
|
||||
<p class="heading-meta domain">{{ domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
{% if not request.impersonation %}
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Check DNS records</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if can_refresh or mail_domain.dns_setup_problem or mail_domain.dns_sync_requested %}
|
||||
<section class="surface" aria-labelledby="mail-dns-setup-heading">
|
||||
<header class="section-heading"><h2 id="mail-dns-setup-heading">Mail DNS setup</h2></header>
|
||||
<div class="editor dns-instructions">
|
||||
{% if mail_domain.dns_setup_problem %}<p class="notice">{{ mail_domain.dns_setup_problem }}</p>{% endif %}
|
||||
{% if mail_domain.dns_sync_requested %}<p>Waiting to update the managed zone.</p>{% endif %}
|
||||
{% if can_refresh %}
|
||||
<form method="post" action="{% url 'panel:mail_dns_setup' mail_domain.pk %}">
|
||||
{% csrf_token %}
|
||||
<button class="button secondary" type="submit">Refresh mail DNS setup</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if report %}
|
||||
<section class="surface" aria-labelledby="results-heading">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2 id="results-heading">DNS results</h2>
|
||||
<p class="heading-meta">Lookups use {% if explicit_resolver %}the configured DNS resolver{% else %}the panel server’s DNS resolver{% endif %}. Cached records can remain visible until their TTL expires.</p>
|
||||
</div>
|
||||
</header>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Check</th><th scope="col">Status</th><th scope="col">DNS answer</th></tr></thead>
|
||||
<tbody>
|
||||
{% for check in report.checks %}
|
||||
<tr>
|
||||
<th scope="row">{{ check.label }}</th>
|
||||
<td>
|
||||
{% if check.state == "ok" %}<span class="status ready">Published</span>
|
||||
{% elif check.state == "attention" %}<span class="status pending">Needs attention</span>
|
||||
{% elif check.state == "missing" %}<span class="status pending">Missing</span>
|
||||
{% elif check.state == "unavailable" %}<span class="status pending">Unavailable</span>
|
||||
{% elif check.state == "optional" %}<span class="status">Optional</span>
|
||||
{% else %}<span class="status">Not checked</span>{% endif %}
|
||||
</td>
|
||||
<td class="dns-answer">
|
||||
<code>{{ check.name }}.</code>
|
||||
<p>{{ check.detail }}</p>
|
||||
{% for record in check.records %}<div><code>{{ record }}</code></div>{% endfor %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="surface" aria-labelledby="dns-provider-heading">
|
||||
<header class="section-heading"><h2 id="dns-provider-heading">Where to edit DNS</h2></header>
|
||||
<div class="editor dns-instructions">
|
||||
{% if report.nameservers %}
|
||||
<p>DNS for <strong>{{ report.zone }}</strong> is served by {{ report.nameservers|join:", " }}.</p>
|
||||
{% elif report %}
|
||||
<p>The active DNS zone or its nameservers could not be determined.</p>
|
||||
{% endif %}
|
||||
{% if zone_matches %}
|
||||
<p>The observed nameservers match the Coulobre zone <strong>{{ zone.domain }}</strong>. Ask the hosting operator to publish updates on the configured local or remote DNS node.</p>
|
||||
{% elif zone %}
|
||||
{% if report.nameservers %}
|
||||
<p>The observed nameservers differ from the saved Coulobre zone <strong>{{ zone.domain }}</strong>. Use the provider serving the active zone.</p>
|
||||
{% else %}
|
||||
<p>A Coulobre zone exists for <strong>{{ zone.domain }}</strong>. Run the check to compare its nameservers with the active zone.</p>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<p>If a third party serves DNS, add the records in that provider's DNS editor. Use the registrar's editor when it also hosts the active DNS zone.</p>
|
||||
<p>Enter the full record name below, or remove the zone suffix if the editor appends it automatically. Use <code>@</code> only at that zone’s apex. Enter TXT values without extra quotes.</p>
|
||||
<ul>
|
||||
<li><strong>MX and addresses.</strong> Use the mail service’s inbound hostname and priority. Publish A and AAAA for the IPv4 and IPv6 addresses it serves. Use a DNS-only host for mail.</li>
|
||||
<li><strong>SPF.</strong> Publish one TXT policy at <code>{{ domain }}.</code>. Include every authorized sender using the IPs or include mechanism supplied by its mail service. Merge senders into an existing SPF record.</li>
|
||||
<li><strong>DKIM.</strong> Copy the provider’s TXT or CNAME at <code>selector._domainkey.{{ domain }}.</code>. Use the exact selector and public value supplied by the signer. Keep the signing key private.</li>
|
||||
<li><strong>DMARC.</strong> Use a TXT at <code>_dmarc.{{ domain }}.</code>. If no policy applies, start with monitoring and set up aggregate reports before choosing an enforcement policy.</li>
|
||||
<li><strong>MTA-STS and TLS-RPT.</strong> Use the mail provider’s published policy ID at <code>_mta-sts.{{ domain }}.</code> and report URI at <code>_smtp._tls.{{ domain }}.</code>. MTA-STS also needs its HTTPS policy.</li>
|
||||
<li><strong>PTR.</strong> Ask the provider that owns the sending IP to set its reverse record. The PTR hostname must resolve back to the IP.{% if sending_ips %} Configured sending IPs: {{ sending_ips|join:", " }}.{% endif %}</li>
|
||||
</ul>
|
||||
{% if entries or dmarc_example %}
|
||||
{% if entries %}
|
||||
<p>These values come from your saved Coulobre zone and the operator’s mail configuration. Confirm they match the active mail service before publishing them.</p>
|
||||
{% endif %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Type</th><th scope="col">Name</th><th scope="col">Value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for entry in entries %}
|
||||
<tr>
|
||||
<th scope="row">{{ entry.kind }}</th>
|
||||
<td>
|
||||
{% with id=forloop.counter|stringformat:"s" %}
|
||||
{% include "hosting/copy_value.html" with key="dns-name-"|add:id label="record name" value=entry.name|add:"." only %}
|
||||
{% endwith %}
|
||||
</td>
|
||||
<td>
|
||||
{% if entry.priority is not None %}<p>Priority {{ entry.priority }}</p>{% endif %}
|
||||
{% with id=forloop.counter|stringformat:"s" %}
|
||||
{% include "hosting/copy_value.html" with key="dns-value-"|add:id label="record value" value=entry.value only %}
|
||||
{% endwith %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% if dmarc_example %}
|
||||
<tr>
|
||||
<th scope="row">TXT<br>DMARC monitoring example</th>
|
||||
<td>{% include "hosting/copy_value.html" with key="dmarc-name" label="DMARC name" value="_dmarc."|add:domain|add:"." only %}</td>
|
||||
<td>{% include "hosting/copy_value.html" with key="dmarc-value" label="DMARC value" value="v=DMARC1; p=none" only %}</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p aria-live="polite" id="copy-field-status"></p>
|
||||
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||
{% endif %}
|
||||
<p>Run the check after publishing. To verify that your mail is signed and passes alignment, send a message and inspect its Authentication-Results header at the recipient.</p>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
@@ -24,17 +24,17 @@
|
||||
<label for="credential-{{ key }}">{{ label }}</label>
|
||||
<div class="form-actions">
|
||||
<input id="credential-{{ key }}" type="text" readonly autocomplete="off" spellcheck="false" value="{{ value }}"{% if key == "password" %} data-secret{% endif %}>
|
||||
<button class="button secondary" type="button" hidden data-copy-credential="credential-{{ key }}">Copy {{ label|lower }}</button>
|
||||
<button class="button secondary" type="button" hidden data-copy-field="credential-{{ key }}">Copy {{ label|lower }}</button>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<p aria-live="polite" id="credential-copy-status"></p>
|
||||
<p aria-live="polite" id="copy-field-status"></p>
|
||||
<div class="form-actions">
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Done</a>
|
||||
{% if rotation_url %}<a class="button secondary" href="{{ rotation_url }}">Rotate password</a>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<script src="{% static 'hosting/credential-copy.js' %}" defer></script>
|
||||
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||
{% else %}
|
||||
<form method="post" class="editor">
|
||||
{% if rotating %}
|
||||
|
||||
@@ -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 %}
|
||||
@@ -0,0 +1,318 @@
|
||||
import base64
|
||||
from unittest.mock import patch
|
||||
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.resolver
|
||||
import dns.rrset
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from coulobre.mail_dns import (
|
||||
Check,
|
||||
LookupUnavailableError,
|
||||
MailDnsReport,
|
||||
check_txt,
|
||||
dkim_key,
|
||||
run_mail_dns,
|
||||
spf_policy,
|
||||
)
|
||||
|
||||
from .mail_dns_setup import sync_mail_dns
|
||||
from .models import (
|
||||
Customer,
|
||||
DnsPublication,
|
||||
HostingAccount,
|
||||
HostingDnsZone,
|
||||
HostingMailbox,
|
||||
HostingMailDomain,
|
||||
MailboxProvisioning,
|
||||
)
|
||||
from .tasks import dispatch_dns_publications, provision_mailbox
|
||||
|
||||
DOMAIN = "example.net"
|
||||
MX = "mx.example.net"
|
||||
IP = "93.184.215.14"
|
||||
DKIM = "v=DKIM1; k=ed25519; p=" + base64.b64encode(bytes(range(32))).decode()
|
||||
|
||||
|
||||
def answer(owner, kind, *records):
|
||||
query = dns.message.make_query(owner + ".", kind)
|
||||
response = dns.message.make_response(query)
|
||||
rrset = dns.rrset.from_text(owner + ".", 60, "IN", kind, *records)
|
||||
response.find_rrset(
|
||||
response.answer, rrset.name, rrset.rdclass, rrset.rdtype, create=True
|
||||
).update(rrset)
|
||||
return dns.resolver.Answer(
|
||||
query.question[0].name, query.question[0].rdtype, 1, response
|
||||
)
|
||||
|
||||
|
||||
class MailDnsRecordsTests(SimpleTestCase):
|
||||
def test_queries_supported_records_and_joins_split_txt(self):
|
||||
key_prefix, key_data = DKIM.split("p=")
|
||||
values = {
|
||||
(DOMAIN, "MX"): answer(DOMAIN, "MX", f"10 {MX}."),
|
||||
(MX, "A"): answer(MX, "A", IP),
|
||||
(DOMAIN, "TXT"): answer(
|
||||
DOMAIN, "TXT", '"v=spf1 ip4:93.184.215.14 -all"', '"unrelated"'
|
||||
),
|
||||
("_dmarc.example.net", "TXT"): answer(
|
||||
"_dmarc.example.net", "TXT", '"v=DMARC1; p=none"'
|
||||
),
|
||||
("news._domainkey.example.net", "TXT"): answer(
|
||||
"news._domainkey.example.net",
|
||||
"TXT",
|
||||
f'"{key_prefix}p=" "{key_data}"',
|
||||
),
|
||||
("_mta-sts.example.net", "TXT"): answer(
|
||||
"_mta-sts.example.net", "TXT", '"v=STSv1; id=20261201"'
|
||||
),
|
||||
("_smtp._tls.example.net", "TXT"): answer(
|
||||
"_smtp._tls.example.net",
|
||||
"TXT",
|
||||
'"v=TLSRPTv1; rua=mailto:tls@example.net"',
|
||||
),
|
||||
("14.215.184.93.in-addr.arpa", "PTR"): answer(
|
||||
"14.215.184.93.in-addr.arpa", "PTR", f"{MX}."
|
||||
),
|
||||
}
|
||||
with patch("coulobre.mail_dns.MailDnsResolver") as factory:
|
||||
resolver = factory.return_value
|
||||
resolver.lookup.side_effect = lambda name, kind: values.get(
|
||||
(name, kind)
|
||||
)
|
||||
resolver.authoritative_zone.return_value = (
|
||||
DOMAIN,
|
||||
("dns.example.net.",),
|
||||
)
|
||||
report = run_mail_dns(
|
||||
DOMAIN, ("news",), expected_mx=MX, sending_ips=(IP,)
|
||||
)
|
||||
self.assertEqual(report.zone, DOMAIN)
|
||||
self.assertEqual(len(report.checks), 7)
|
||||
self.assertEqual({check.state for check in report.checks}, {"ok"})
|
||||
self.assertEqual(report.checks[3].records, (DKIM,))
|
||||
|
||||
def test_reports_invalid_or_unavailable_records(self):
|
||||
owner = "_dmarc.example.net"
|
||||
with patch("coulobre.mail_dns.MailDnsResolver") as factory:
|
||||
resolver = factory.return_value
|
||||
resolver.lookup.side_effect = LookupUnavailableError
|
||||
self.assertEqual(
|
||||
check_txt(resolver, "DMARC", owner, "v=DMARC1", None).state,
|
||||
"unavailable",
|
||||
)
|
||||
resolver.lookup.side_effect = None
|
||||
resolver.lookup.return_value = answer(
|
||||
owner, "TXT", '"v=DMARC1; p=none"', '"v=DMARC1; p=reject"'
|
||||
)
|
||||
self.assertEqual(
|
||||
check_txt(resolver, "DMARC", owner, "v=DMARC1", None).state,
|
||||
"attention",
|
||||
)
|
||||
self.assertEqual(dkim_key("v=DKIM1; p=")[0], "attention")
|
||||
self.assertEqual(spf_policy("v=spf1 +all")[0], "attention")
|
||||
self.assertEqual(spf_policy("v=spf1 ip4:fd00::7 -all")[0], "attention")
|
||||
|
||||
|
||||
@override_settings(
|
||||
LOCAL_DNS_PUBLISHING=True,
|
||||
LOCAL_MAILBOX_PROVISIONING=True,
|
||||
MANAGE_MAIL_DNS=True,
|
||||
MAIL_MX_HOST=MX,
|
||||
MAIL_MX_IPS=(IP,),
|
||||
MAIL_SENDING_IPS=(IP,),
|
||||
)
|
||||
class MailDnsPanelTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.customer = Customer.objects.create(
|
||||
user=users.create_user("customer")
|
||||
)
|
||||
cls.other = Customer.objects.create(user=users.create_user("other"))
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Example", primary_domain=DOMAIN, customer=cls.customer
|
||||
)
|
||||
cls.domain = HostingMailDomain.objects.create(
|
||||
account=cls.account, domain=DOMAIN
|
||||
)
|
||||
cls.mailbox = HostingMailbox.objects.create(
|
||||
mail_domain=cls.domain, local_part="hello"
|
||||
)
|
||||
|
||||
def zone(self, **values):
|
||||
return HostingDnsZone.objects.create(
|
||||
account=self.account,
|
||||
domain=DOMAIN,
|
||||
nameservers=["ns.other.example"],
|
||||
responsible_name="hostmaster.example.net",
|
||||
**values,
|
||||
)
|
||||
|
||||
def test_scopes_check_and_renders_external_copy_fields(self):
|
||||
url = reverse("panel:mail_dns_check", args=[self.domain.pk])
|
||||
report = MailDnsReport(
|
||||
DOMAIN,
|
||||
("dns.third-party.example.",),
|
||||
(Check("SPF", DOMAIN, "ok", "Public policy", ("v=spf1 -all",)),),
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.mail_dns_views.run_mail_dns", return_value=report
|
||||
) as check:
|
||||
self.client.force_login(self.other.user)
|
||||
self.assertEqual(
|
||||
self.client.post(url, {"selectors": "test"}).status_code, 404
|
||||
)
|
||||
self.client.force_login(self.customer.user)
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()), url
|
||||
)
|
||||
page = self.client.get(url)
|
||||
self.assertContains(page, "registrar")
|
||||
self.assertContains(page, 'value="mx.example.net."')
|
||||
self.assertContains(page, 'value="v=spf1 ip4:93.184.215.14 ~all"')
|
||||
self.assertContains(page, 'data-copy-field="dns-name-1"')
|
||||
self.assertContains(
|
||||
self.client.post(url, {"selectors": "../outside"}),
|
||||
"Enter selector names only",
|
||||
)
|
||||
check.assert_not_called()
|
||||
result = self.client.post(url, {"selectors": "news, news a.b"})
|
||||
self.assertContains(result, "dns.third-party.example.")
|
||||
self.assertContains(result, "Public policy")
|
||||
self.assertIn("no-store", result["Cache-Control"])
|
||||
check.assert_called_once_with(
|
||||
DOMAIN,
|
||||
("news", "a.b"),
|
||||
nameservers=(),
|
||||
expected_mx=MX,
|
||||
signing_record="",
|
||||
sending_ips=(IP,),
|
||||
)
|
||||
|
||||
def test_first_mailbox_adds_public_records_and_retry_keeps_serial(self):
|
||||
zone = self.zone(manage_mail_dns=True, serial=5)
|
||||
job = MailboxProvisioning.objects.create(mailbox=self.mailbox)
|
||||
public_key = generate_private_key(
|
||||
public_exponent=65537, key_size=2048
|
||||
).public_key()
|
||||
dkim = (
|
||||
"v=DKIM1; k=rsa; p="
|
||||
+ base64.b64encode(
|
||||
public_key.public_bytes(Encoding.DER, PublicFormat.PKCS1)
|
||||
).decode()
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.tasks.provision_signing_mailbox",
|
||||
return_value=dkim,
|
||||
):
|
||||
provision_mailbox(job.pk)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.state, "configured")
|
||||
self.domain.refresh_from_db()
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(self.domain.dkim_record, dkim)
|
||||
self.assertEqual(dkim_key(dkim, expected=dkim)[0], "ok")
|
||||
self.assertEqual(dkim_key(DKIM, expected=dkim)[0], "attention")
|
||||
self.assertEqual(zone.serial, 6)
|
||||
self.assertEqual(
|
||||
zone.mx_records, [{"name": DOMAIN, "priority": 10, "exchange": MX}]
|
||||
)
|
||||
self.assertEqual(zone.addresses, [{"name": MX, "address": IP}])
|
||||
self.assertEqual(
|
||||
{item["name"]: item["text"] for item in zone.txt_records},
|
||||
{
|
||||
DOMAIN: f"v=spf1 ip4:{IP} ~all",
|
||||
"_dmarc.example.net": "v=DMARC1; p=none",
|
||||
"coulobre._domainkey.example.net": dkim,
|
||||
},
|
||||
)
|
||||
publication = DnsPublication.objects.get(zone=zone)
|
||||
self.assertEqual(publication.manifest, zone.spec.manifest())
|
||||
sync_mail_dns(self.domain, public_key=dkim)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 6)
|
||||
|
||||
def test_dns_sync_waits_for_inflight_publication(self):
|
||||
zone = self.zone(manage_mail_dns=True)
|
||||
publication = DnsPublication.objects.create(
|
||||
zone=zone, serial=zone.serial, manifest=zone.spec.manifest()
|
||||
)
|
||||
sync_mail_dns(self.domain, public_key=DKIM)
|
||||
self.domain.refresh_from_db()
|
||||
self.assertTrue(self.domain.dns_sync_requested)
|
||||
publication.finished_at = timezone.now()
|
||||
publication.published_serial = zone.serial
|
||||
publication.save(update_fields=["finished_at", "published_serial"])
|
||||
with patch(
|
||||
"coulobre.hosting.tasks.publish_dns_zone.apply_async"
|
||||
) as dispatch:
|
||||
dispatch_dns_publications()
|
||||
self.domain.refresh_from_db()
|
||||
publication.refresh_from_db()
|
||||
self.assertFalse(self.domain.dns_sync_requested)
|
||||
self.assertEqual(publication.serial, 2)
|
||||
dispatch.assert_called_once()
|
||||
|
||||
def test_external_zone_and_unpublished_edits_are_untouched(self):
|
||||
zone = self.zone(manage_mail_dns=False, serial=12)
|
||||
sync_mail_dns(self.domain, public_key=DKIM)
|
||||
self.domain.refresh_from_db()
|
||||
self.assertEqual(self.domain.dkim_record, DKIM)
|
||||
self.assertFalse(DnsPublication.objects.exists())
|
||||
zone.manage_mail_dns = True
|
||||
zone.save(update_fields=["manage_mail_dns"])
|
||||
snapshot = DnsPublication.objects.create(
|
||||
zone=zone,
|
||||
serial=11,
|
||||
manifest=zone.spec.manifest(),
|
||||
finished_at=timezone.now(),
|
||||
published_serial=11,
|
||||
)
|
||||
sync_mail_dns(self.domain, public_key=DKIM)
|
||||
zone.refresh_from_db()
|
||||
self.domain.refresh_from_db()
|
||||
snapshot.refresh_from_db()
|
||||
self.assertIn("saved zone revision", self.domain.dns_setup_problem)
|
||||
self.assertEqual(zone.txt_records, [])
|
||||
self.assertEqual(snapshot.serial, 11)
|
||||
|
||||
def test_keeps_existing_policies_and_conflicting_mx(self):
|
||||
current = [
|
||||
{
|
||||
"name": DOMAIN,
|
||||
"text": "v=spf1 include:_spf.sender.example -all",
|
||||
},
|
||||
{"name": "_dmarc.example.net", "text": "v=DMARC1; p=reject"},
|
||||
]
|
||||
zone = self.zone(
|
||||
manage_mail_dns=True,
|
||||
txt_records=current,
|
||||
mx_records=[
|
||||
{
|
||||
"name": DOMAIN,
|
||||
"priority": 10,
|
||||
"exchange": "mx.other.example",
|
||||
}
|
||||
],
|
||||
)
|
||||
sync_mail_dns(self.domain, public_key=DKIM)
|
||||
self.assertFalse(DnsPublication.objects.filter(zone=zone).exists())
|
||||
self.domain.refresh_from_db()
|
||||
self.assertIn("Review the current MX", self.domain.dns_setup_problem)
|
||||
zone.mx_records = []
|
||||
zone.save(update_fields=["mx_records"])
|
||||
sync_mail_dns(self.domain, public_key=DKIM)
|
||||
zone.refresh_from_db()
|
||||
self.domain.refresh_from_db()
|
||||
self.assertIn(
|
||||
"Existing SPF policy kept", self.domain.dns_setup_problem
|
||||
)
|
||||
self.assertEqual(zone.txt_records[:2], current)
|
||||
@@ -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):
|
||||
|
||||
@@ -5,6 +5,7 @@ from . import views
|
||||
from .backup_restores import RestoreKind
|
||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||
from .health_views import ServiceHealthView
|
||||
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
||||
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
|
||||
from .reseller_views import (
|
||||
ResellerCreate,
|
||||
@@ -13,6 +14,7 @@ from .reseller_views import (
|
||||
ResellerList,
|
||||
)
|
||||
from .retirement_views import RetirementList, RetirementView
|
||||
from .roundcube import RoundcubeLaunch, redeem_roundcube
|
||||
|
||||
app_name = "panel"
|
||||
|
||||
@@ -165,6 +167,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(),
|
||||
@@ -205,6 +213,16 @@ urlpatterns = [
|
||||
views.RequestDnsPublication.as_view(),
|
||||
name="dns_zone_publish",
|
||||
),
|
||||
path(
|
||||
"mail-domains/<int:pk>/dns-check/",
|
||||
MailDnsCheckView.as_view(),
|
||||
name="mail_dns_check",
|
||||
),
|
||||
path(
|
||||
"mail-domains/<int:pk>/dns-setup/",
|
||||
RequestMailDnsSetup.as_view(),
|
||||
name="mail_dns_setup",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/mailboxes/new/",
|
||||
views.MailboxCreate.as_view(),
|
||||
|
||||
@@ -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):
|
||||
@@ -513,6 +517,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
zone.domain == self.object.primary_domain for zone in zones
|
||||
)
|
||||
if tenant or user.has_perm(VIEW_MAILBOXES):
|
||||
context["mail_domains"] = self.object.mail_domains.order_by(
|
||||
"domain"
|
||||
)
|
||||
mailboxes = HostingMailbox.objects.filter(
|
||||
mail_domain__account=self.object
|
||||
).select_related("mail_domain")
|
||||
@@ -525,6 +532,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
|
||||
|
||||
@@ -1505,6 +1523,7 @@ class DnsZoneEdit(DnsZoneEditor):
|
||||
def get_initial(self):
|
||||
return {
|
||||
"serial": self.zone.serial,
|
||||
"manage_mail_dns": self.zone.manage_mail_dns,
|
||||
"nameservers": "\n".join(self.zone.nameservers),
|
||||
"responsible_name": self.zone.responsible_name,
|
||||
"addresses": "\n".join(
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
import base64
|
||||
import binascii
|
||||
import ipaddress
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
from time import monotonic
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import dns.exception
|
||||
import dns.name
|
||||
import dns.resolver
|
||||
import dns.reversename
|
||||
from cryptography.exceptions import UnsupportedAlgorithm
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
|
||||
from cryptography.hazmat.primitives.serialization import (
|
||||
Encoding,
|
||||
PublicFormat,
|
||||
load_der_public_key,
|
||||
)
|
||||
|
||||
MAX_SELECTORS = 4
|
||||
MAX_MX_HOSTS = 4
|
||||
MAX_RECORDS = 8
|
||||
MANAGED_DKIM_SELECTOR = "coulobre"
|
||||
SELECTOR = re.compile(
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
|
||||
r"(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*",
|
||||
re.ASCII | re.IGNORECASE,
|
||||
)
|
||||
SPF_MECHANISM = re.compile(
|
||||
r"[+?~-]?(?:all|(?:a|mx)(?:[:/].+)?|ptr(?::.+)?|"
|
||||
r"(?:include|ip4|ip6|exists):.+)",
|
||||
re.ASCII | re.IGNORECASE,
|
||||
)
|
||||
SPF_MODIFIER = re.compile(r"[a-zA-Z][a-zA-Z0-9_.-]*=\S+")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Check:
|
||||
label: str
|
||||
name: str
|
||||
state: str
|
||||
detail: str
|
||||
records: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailDnsReport:
|
||||
zone: str
|
||||
nameservers: tuple[str, ...]
|
||||
checks: tuple[Check, ...]
|
||||
|
||||
|
||||
class LookupUnavailableError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MailDnsResolver:
|
||||
def __init__(self, nameservers=()):
|
||||
self.deadline = monotonic() + 7
|
||||
self.resolver = None
|
||||
try:
|
||||
self.resolver = dns.resolver.Resolver(configure=not nameservers)
|
||||
except dns.exception.DNSException:
|
||||
return
|
||||
if nameservers:
|
||||
self.resolver.nameservers = list(nameservers)
|
||||
self.resolver.timeout = 1
|
||||
|
||||
def lifetime(self):
|
||||
remaining = self.deadline - monotonic()
|
||||
if self.resolver is None or remaining <= 0:
|
||||
raise LookupUnavailableError
|
||||
return min(remaining, 2)
|
||||
|
||||
def lookup(self, name, record_type):
|
||||
try:
|
||||
lifetime = self.lifetime()
|
||||
answer = self.resolver.resolve(
|
||||
name + ".", record_type, search=False, lifetime=lifetime
|
||||
)
|
||||
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
|
||||
return None
|
||||
except dns.exception.DNSException as error:
|
||||
raise LookupUnavailableError from error
|
||||
return answer
|
||||
|
||||
def authoritative_zone(self, name):
|
||||
try:
|
||||
zone = dns.resolver.zone_for_name(
|
||||
name + ".", resolver=self.resolver, lifetime=self.lifetime()
|
||||
)
|
||||
if zone == dns.name.root:
|
||||
return "", ()
|
||||
owner = zone.to_text(omit_final_dot=True).lower()
|
||||
records = self.lookup(owner, "NS")
|
||||
except (dns.exception.DNSException, LookupUnavailableError):
|
||||
return "", ()
|
||||
return owner, tuple(
|
||||
sorted(record.target.to_text().lower() for record in records or ())
|
||||
)[:MAX_RECORDS]
|
||||
|
||||
|
||||
def run_mail_dns(
|
||||
domain,
|
||||
selectors,
|
||||
*,
|
||||
nameservers=(),
|
||||
expected_mx="",
|
||||
signing_record="",
|
||||
sending_ips=(),
|
||||
):
|
||||
resolver = MailDnsResolver(nameservers)
|
||||
checks = [
|
||||
check_txt(resolver, "SPF", domain, "v=spf1", spf_policy),
|
||||
check_txt(
|
||||
resolver,
|
||||
"DMARC",
|
||||
f"_dmarc.{domain}",
|
||||
"v=DMARC1",
|
||||
dmarc_policy,
|
||||
),
|
||||
]
|
||||
for selector in selectors:
|
||||
expected = signing_record if selector == MANAGED_DKIM_SELECTOR else ""
|
||||
checks.append(
|
||||
check_txt(
|
||||
resolver,
|
||||
f"DKIM ({selector})",
|
||||
f"{selector}._domainkey.{domain}",
|
||||
"v=DKIM1",
|
||||
partial(dkim_key, expected=expected),
|
||||
)
|
||||
)
|
||||
if not selectors:
|
||||
checks.append(
|
||||
Check("DKIM", domain, "not_checked", "Enter the signing selector.")
|
||||
)
|
||||
checks.insert(0, check_mx(resolver, domain, expected_mx))
|
||||
checks.extend(check_ptr(resolver, address) for address in sending_ips)
|
||||
zone, delegated_servers = resolver.authoritative_zone(domain)
|
||||
checks.extend(
|
||||
(
|
||||
check_txt(
|
||||
resolver,
|
||||
"MTA-STS",
|
||||
f"_mta-sts.{domain}",
|
||||
"v=STSv1",
|
||||
sts_policy,
|
||||
),
|
||||
check_txt(
|
||||
resolver,
|
||||
"TLS-RPT",
|
||||
f"_smtp._tls.{domain}",
|
||||
"v=TLSRPTv1",
|
||||
tls_reporting,
|
||||
),
|
||||
)
|
||||
)
|
||||
return MailDnsReport(zone, delegated_servers, tuple(checks))
|
||||
|
||||
|
||||
def check_mx(resolver, domain, expected):
|
||||
try:
|
||||
answer = resolver.lookup(domain, "MX")
|
||||
except LookupUnavailableError:
|
||||
return unavailable("MX", domain)
|
||||
if not answer:
|
||||
return Check("MX", domain, "missing", "Publish an explicit MX record.")
|
||||
routes = sorted(
|
||||
(entry.preference, entry.exchange.to_text().lower())
|
||||
for entry in answer
|
||||
)
|
||||
records = tuple(f"{priority} {host}" for priority, host in routes)
|
||||
if routes == [(0, ".")]:
|
||||
return Check(
|
||||
"MX", domain, "attention", "This null MX disables mail.", records
|
||||
)
|
||||
if any(host == "." for _, host in routes):
|
||||
return Check(
|
||||
"MX",
|
||||
domain,
|
||||
"attention",
|
||||
"Remove the conflicting null MX.",
|
||||
records,
|
||||
)
|
||||
hosts = tuple(dict.fromkeys(host.rstrip(".") for _, host in routes))
|
||||
results = [check_mx_host(resolver, host) for host in hosts[:MAX_MX_HOSTS]]
|
||||
if len(hosts) > MAX_MX_HOSTS:
|
||||
results.append(
|
||||
("attention", "Only the first four targets were checked.")
|
||||
)
|
||||
if expected and expected not in hosts:
|
||||
results.append(
|
||||
("attention", f"Expected {expected} among the targets.")
|
||||
)
|
||||
states = {state for state, _ in results}
|
||||
state = next(
|
||||
item for item in ("attention", "unavailable", "ok") if item in states
|
||||
)
|
||||
return Check(
|
||||
"MX",
|
||||
domain,
|
||||
state,
|
||||
" ".join(detail for _, detail in results),
|
||||
records[:MAX_RECORDS],
|
||||
)
|
||||
|
||||
|
||||
def check_mx_host(resolver, host):
|
||||
addresses = []
|
||||
unavailable_types = []
|
||||
for kind in ("A", "AAAA"):
|
||||
try:
|
||||
answer = resolver.lookup(host, kind)
|
||||
except LookupUnavailableError:
|
||||
unavailable_types.append(kind)
|
||||
continue
|
||||
if answer:
|
||||
if (
|
||||
answer.canonical_name.to_text(omit_final_dot=True).lower()
|
||||
!= host
|
||||
):
|
||||
return "attention", f"{host} is an alias. Use a direct target."
|
||||
addresses.extend(
|
||||
ipaddress.ip_address(row.address) for row in answer
|
||||
)
|
||||
if any(
|
||||
not address.is_global or address.is_multicast for address in addresses
|
||||
):
|
||||
return "attention", f"{host} has a non-public address."
|
||||
if unavailable_types:
|
||||
return "unavailable", f"Could not check all addresses for {host}."
|
||||
if not addresses:
|
||||
return "attention", f"{host} has no A or AAAA record."
|
||||
return "ok", f"{host} resolves to public addresses."
|
||||
|
||||
|
||||
def check_ptr(resolver, address):
|
||||
label = f"PTR ({address})"
|
||||
owner = dns.reversename.from_address(address).to_text(omit_final_dot=True)
|
||||
try:
|
||||
records = resolver.lookup(owner, "PTR")
|
||||
except LookupUnavailableError:
|
||||
return unavailable(label, owner)
|
||||
if not records:
|
||||
return Check(
|
||||
label, owner, "missing", "Ask the IP provider to set PTR."
|
||||
)
|
||||
targets = tuple(record.target.to_text().lower() for record in records)
|
||||
if len(targets) != 1:
|
||||
return Check(
|
||||
label,
|
||||
owner,
|
||||
"attention",
|
||||
"Use one canonical mail hostname.",
|
||||
targets[:MAX_RECORDS],
|
||||
)
|
||||
host = targets[0].rstrip(".")
|
||||
kind = "A" if ipaddress.ip_address(address).version == 4 else "AAAA"
|
||||
try:
|
||||
forward = resolver.lookup(host, kind)
|
||||
except LookupUnavailableError:
|
||||
return unavailable(label, owner)
|
||||
if not forward or all(
|
||||
ipaddress.ip_address(row.address) != ipaddress.ip_address(address)
|
||||
for row in forward
|
||||
):
|
||||
return Check(
|
||||
label,
|
||||
owner,
|
||||
"attention",
|
||||
"The PTR target must resolve back to this IP.",
|
||||
targets,
|
||||
)
|
||||
return Check(label, owner, "ok", "Forward and reverse DNS agree.", targets)
|
||||
|
||||
|
||||
def check_txt(resolver, label, name, version, validate):
|
||||
try:
|
||||
answer = resolver.lookup(name, "TXT")
|
||||
except LookupUnavailableError:
|
||||
return unavailable(label, name)
|
||||
records = tuple(
|
||||
b"".join(record.strings).decode("ascii", errors="replace")
|
||||
for record in answer or ()
|
||||
)
|
||||
matches = tuple(
|
||||
record for record in records if matches_version(record, version)
|
||||
)
|
||||
if version == "v=DKIM1":
|
||||
# A DKIM key can omit its version tag.
|
||||
matches = records
|
||||
if not matches:
|
||||
detail = "The record is missing."
|
||||
if version == "v=DMARC1":
|
||||
detail = "No direct record. A parent domain's policy may apply."
|
||||
elif version == "v=STSv1" or version == "v=TLSRPTv1":
|
||||
return Check(label, name, "optional", "Optional record absent.")
|
||||
return Check(label, name, "missing", detail)
|
||||
if len(matches) > 1:
|
||||
state, detail = (
|
||||
"attention",
|
||||
"Publish one matching record at this name.",
|
||||
)
|
||||
elif len(matches[0]) > 4096:
|
||||
state, detail = (
|
||||
"attention",
|
||||
"The record exceeds the checker size limit.",
|
||||
)
|
||||
else:
|
||||
state, detail = validate(matches[0])
|
||||
if answer.canonical_name.to_text().lower() != f"{name}.".lower():
|
||||
detail += f" Resolves through {answer.canonical_name.to_text()}."
|
||||
return Check(
|
||||
label,
|
||||
name,
|
||||
state,
|
||||
detail,
|
||||
tuple(record[:2048] for record in matches[:MAX_RECORDS]),
|
||||
)
|
||||
|
||||
|
||||
def unavailable(label, name):
|
||||
return Check(label, name, "unavailable", "DNS lookup unavailable.")
|
||||
|
||||
|
||||
def matches_version(record, version):
|
||||
if version == "v=spf1":
|
||||
return record.lower() == version or record.lower().startswith(
|
||||
version + " "
|
||||
)
|
||||
first = record.split(";", 1)[0]
|
||||
key, separator, value = first.partition("=")
|
||||
return separator and key.strip() == "v" and value.strip() == version[2:]
|
||||
|
||||
|
||||
def spf_policy(record):
|
||||
terms = record.lower().split()[1:]
|
||||
if any(
|
||||
not (SPF_MECHANISM.fullmatch(term) or SPF_MODIFIER.fullmatch(term))
|
||||
for term in terms
|
||||
):
|
||||
return "attention", "A mechanism or modifier is not recognized."
|
||||
for term in terms:
|
||||
mechanism = term.lstrip("+?~-")
|
||||
if mechanism.startswith(("ip4:", "ip6:")):
|
||||
name, address = mechanism.split(":", 1)
|
||||
try:
|
||||
if ipaddress.ip_network(address, strict=False).version != int(
|
||||
name[-1]
|
||||
):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
return (
|
||||
"attention",
|
||||
"An IP mechanism has an invalid address or CIDR.",
|
||||
)
|
||||
if "all" in terms or "+all" in terms:
|
||||
return "attention", "The policy contains an all-senders authorization."
|
||||
if not terms:
|
||||
return "attention", "The policy does not list any senders."
|
||||
return (
|
||||
"ok",
|
||||
"One SPF policy published. Includes and senders were not evaluated.",
|
||||
)
|
||||
|
||||
|
||||
def read_tags(record):
|
||||
tags = {}
|
||||
# One trailing semicolon is allowed.
|
||||
for item in record.rstrip().removesuffix(";").split(";"):
|
||||
key, separator, value = item.partition("=")
|
||||
key = key.strip()
|
||||
if not separator or not key or key in tags:
|
||||
return {}
|
||||
tags[key] = value.strip()
|
||||
return tags
|
||||
|
||||
|
||||
def dmarc_policy(record):
|
||||
tags = read_tags(record)
|
||||
policy = tags.get("p")
|
||||
policies = {"none", "quarantine", "reject"}
|
||||
if policy not in policies or any(
|
||||
tags.get(name, policy) not in policies for name in ("sp", "np")
|
||||
):
|
||||
return (
|
||||
"attention",
|
||||
"Check the policy tags. Use none, quarantine or reject.",
|
||||
)
|
||||
if any(
|
||||
tags.get(name, "r") not in {"r", "s"} for name in ("adkim", "aspf")
|
||||
):
|
||||
return "attention", "The alignment tags must be r or s."
|
||||
if policy == "none":
|
||||
return (
|
||||
"ok",
|
||||
"Monitoring policy (p=none). Review reports before enforcement.",
|
||||
)
|
||||
return "ok", f"Published enforcement policy (p={policy})."
|
||||
|
||||
|
||||
def dkim_key(record, *, expected=""):
|
||||
tags = read_tags(record)
|
||||
if "p" not in tags or (
|
||||
"v" in tags and (next(iter(tags)) != "v" or tags["v"] != "DKIM1")
|
||||
):
|
||||
return "attention", "Check the DKIM key tags."
|
||||
if not tags["p"]:
|
||||
return "attention", "The published key is revoked (empty p=)."
|
||||
try:
|
||||
public = decode_key(tags["p"])
|
||||
algorithm = tags.get("k", "rsa")
|
||||
if algorithm == "ed25519" and len(public) == 32:
|
||||
if expected:
|
||||
return "attention", "The key type differs from the mail node."
|
||||
return "ok", "Ed25519 public key published."
|
||||
if algorithm == "rsa":
|
||||
key = load_der_public_key(public)
|
||||
if isinstance(key, RSAPublicKey):
|
||||
if key.key_size < 1024:
|
||||
return (
|
||||
"attention",
|
||||
"The RSA key is shorter than 1024 bits.",
|
||||
)
|
||||
if key.key_size < 2048:
|
||||
return (
|
||||
"attention",
|
||||
"RSA key published. Prefer at least 2048 bits.",
|
||||
)
|
||||
if expected and key.public_bytes(
|
||||
Encoding.DER, PublicFormat.PKCS1
|
||||
) != decode_key(read_tags(expected).get("p", "")):
|
||||
return (
|
||||
"attention",
|
||||
"The public key differs from the mail node's key.",
|
||||
)
|
||||
return "ok", f"RSA public key published ({key.key_size} bits)."
|
||||
except (binascii.Error, ValueError, UnsupportedAlgorithm):
|
||||
pass
|
||||
return "attention", "The public key or key type is invalid or unsupported."
|
||||
|
||||
|
||||
def decode_key(value):
|
||||
data = re.sub(r"[ \t\r\n]", "", value)
|
||||
return base64.b64decode(data, validate=True)
|
||||
|
||||
|
||||
def sts_policy(record):
|
||||
policy_id = read_tags(record).get("id", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9]{1,32}", policy_id):
|
||||
return "attention", "Supply a policy ID of 1 to 32 letters or digits."
|
||||
return "ok", "DNS policy ID published. The HTTPS policy was not checked."
|
||||
|
||||
|
||||
def tls_reporting(record):
|
||||
tags = read_tags(record)
|
||||
addresses = tags.get("rua", "").split(",")
|
||||
try:
|
||||
destinations = [urlsplit(item.strip()) for item in addresses]
|
||||
valid = all(
|
||||
(
|
||||
uri.scheme == "mailto"
|
||||
and re.fullmatch(r"[^@\s]+@[^@\s]+", uri.path)
|
||||
)
|
||||
or (
|
||||
uri.scheme == "https" and uri.hostname and uri.username is None
|
||||
)
|
||||
for uri in destinations
|
||||
)
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid:
|
||||
return "attention", "Supply a mailto or HTTPS report destination."
|
||||
return "ok", "SMTP TLS reporting record published."
|
||||
@@ -102,6 +102,26 @@ class MailboxQuotaUpdate:
|
||||
return {"operation": "set_quota", "mailbox": self.mailbox.manifest()}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MailboxSigningRequest:
|
||||
mailbox: MailboxSpec
|
||||
|
||||
def __post_init__(self):
|
||||
from .mail_dns import MANAGED_DKIM_SELECTOR
|
||||
|
||||
owner = f"{MANAGED_DKIM_SELECTOR}._domainkey.{self.mailbox.domain}"
|
||||
if len(owner) > 253:
|
||||
raise ValueError(
|
||||
"The mail domain is too long for the DKIM selector."
|
||||
)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"operation": "provision_with_signing",
|
||||
"mailbox": self.mailbox.manifest(),
|
||||
}
|
||||
|
||||
|
||||
def parse_mailbox_request(data):
|
||||
return parse_retirement(
|
||||
data, MailboxSpec.from_manifest, parse_mailbox_apply
|
||||
@@ -109,12 +129,15 @@ def parse_mailbox_request(data):
|
||||
|
||||
|
||||
def parse_mailbox_apply(data):
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
and data.keys() == {"operation", "mailbox"}
|
||||
and data["operation"] == "set_quota"
|
||||
):
|
||||
return MailboxQuotaUpdate(MailboxSpec.from_manifest(data["mailbox"]))
|
||||
if isinstance(data, dict) and data.keys() == {"operation", "mailbox"}:
|
||||
if data["operation"] == "set_quota":
|
||||
return MailboxQuotaUpdate(
|
||||
MailboxSpec.from_manifest(data["mailbox"])
|
||||
)
|
||||
if data["operation"] == "provision_with_signing":
|
||||
return MailboxSigningRequest(
|
||||
MailboxSpec.from_manifest(data["mailbox"])
|
||||
)
|
||||
return parse_service_request(data, MailboxSpec.from_manifest)
|
||||
|
||||
|
||||
@@ -131,6 +154,12 @@ def apply_mailbox_request(request):
|
||||
from .mail_node_quota import set_mailbox_quota
|
||||
|
||||
set_mailbox_quota(request.mailbox)
|
||||
elif isinstance(request, MailboxSigningRequest):
|
||||
from .mail_node_apply import apply_mailbox
|
||||
from .mail_node_dkim import provision_dkim_key
|
||||
|
||||
apply_mailbox(request.mailbox)
|
||||
return {"dkim": provision_dkim_key(request.mailbox.domain)}
|
||||
else:
|
||||
from .mail_node_apply import apply_mailbox
|
||||
|
||||
@@ -174,7 +203,10 @@ def main(argv=None):
|
||||
|
||||
if args.command == "apply-request":
|
||||
return serve_apply_request(
|
||||
MANIFEST_VERSION, parse_mailbox_request, apply_mailbox_request
|
||||
MANIFEST_VERSION,
|
||||
parse_mailbox_request,
|
||||
apply_mailbox_request,
|
||||
include_result=True,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import base64
|
||||
import grp
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.exceptions import UnsupportedAlgorithm
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import (
|
||||
RSAPrivateKey,
|
||||
generate_private_key,
|
||||
)
|
||||
from cryptography.hazmat.primitives.serialization import (
|
||||
Encoding,
|
||||
NoEncryption,
|
||||
PrivateFormat,
|
||||
PublicFormat,
|
||||
load_pem_private_key,
|
||||
)
|
||||
|
||||
from .mail_dns import MANAGED_DKIM_SELECTOR
|
||||
from .node_files import locked_root_directory, read_root_file, write_new_file
|
||||
|
||||
KEY_DIRECTORY = Path("/etc/rspamd/coulobre-dkim")
|
||||
SIGNER_GROUP = "_rspamd"
|
||||
|
||||
|
||||
def provision_dkim_key(domain):
|
||||
if not KEY_DIRECTORY.exists():
|
||||
raise ValueError("Set up the Rspamd DKIM directory on the mail node.")
|
||||
key_path = KEY_DIRECTORY / f"{domain}.{MANAGED_DKIM_SELECTOR}.key"
|
||||
with locked_root_directory(KEY_DIRECTORY):
|
||||
try:
|
||||
signer_group = grp.getgrnam(SIGNER_GROUP).gr_gid
|
||||
except KeyError:
|
||||
raise ValueError(
|
||||
"Install and configure Rspamd DKIM signing."
|
||||
) from None
|
||||
directory = KEY_DIRECTORY.stat()
|
||||
if (
|
||||
directory.st_gid != signer_group
|
||||
or directory.st_mode & 0o777 != 0o750
|
||||
):
|
||||
raise ValueError(
|
||||
"Set the DKIM directory to mode 0750 and the Rspamd group."
|
||||
)
|
||||
try:
|
||||
pem = read_root_file(key_path, mode=0o640)
|
||||
except FileNotFoundError:
|
||||
key = generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(
|
||||
Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()
|
||||
)
|
||||
write_new_file(
|
||||
key_path, pem.decode("ascii"), mode=0o640, group=signer_group
|
||||
)
|
||||
else:
|
||||
if key_path.stat().st_gid != signer_group:
|
||||
raise ValueError("The DKIM key has the wrong group.")
|
||||
try:
|
||||
key = load_pem_private_key(pem.encode("ascii"), password=None)
|
||||
except (TypeError, ValueError, UnsupportedAlgorithm):
|
||||
raise ValueError(
|
||||
"Could not read the existing DKIM key."
|
||||
) from None
|
||||
if not isinstance(key, RSAPrivateKey) or key.key_size < 2048:
|
||||
raise ValueError(
|
||||
"The DKIM key must be RSA with at least 2048 bits."
|
||||
)
|
||||
public = key.public_key().public_bytes(
|
||||
Encoding.DER, PublicFormat.PKCS1
|
||||
)
|
||||
return "v=DKIM1; k=rsa; p=" + base64.b64encode(public).decode("ascii")
|
||||
@@ -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):
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import os
|
||||
import re
|
||||
from ipaddress import ip_address
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
from .domain_names import canonical_domain
|
||||
from .service_health import load_health_targets
|
||||
|
||||
|
||||
@@ -14,6 +17,29 @@ def required_env(name):
|
||||
return value
|
||||
|
||||
|
||||
def ip_addresses_env(name, limit):
|
||||
values = os.environ.get(name, "").split(",")
|
||||
try:
|
||||
if any("%" in value for value in values):
|
||||
raise ValueError
|
||||
addresses = tuple(
|
||||
dict.fromkeys(
|
||||
str(ip_address(value.strip()))
|
||||
for value in values
|
||||
if value.strip()
|
||||
)
|
||||
)
|
||||
except ValueError:
|
||||
raise ImproperlyConfigured(
|
||||
f"Set literal IP addresses in {name}."
|
||||
) from None
|
||||
if len(addresses) > limit:
|
||||
raise ImproperlyConfigured(
|
||||
f"Set up to {limit} unscoped IP addresses in {name}."
|
||||
)
|
||||
return addresses
|
||||
|
||||
|
||||
SECRET_KEY = required_env("COULOBRE_SECRET_KEY")
|
||||
HTTPS_PROXY = os.environ.get("COULOBRE_HTTPS_PROXY") == "1"
|
||||
DEBUG = not HTTPS_PROXY and os.environ.get("COULOBRE_DEBUG") == "1"
|
||||
@@ -157,6 +183,30 @@ LOCAL_MAILBOX_CREDENTIALS = (
|
||||
os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS") == "1"
|
||||
)
|
||||
MAIL_IMAP_HOST = os.environ.get("COULOBRE_MAIL_IMAP_HOST", "").strip()
|
||||
MAIL_DNS_RESOLVERS = ip_addresses_env("COULOBRE_MAIL_DNS_RESOLVERS", 3)
|
||||
MAIL_SENDING_IPS = ip_addresses_env("COULOBRE_MAIL_SENDING_IPS", 4)
|
||||
MAIL_MX_IPS = ip_addresses_env("COULOBRE_MAIL_MX_IPS", 4)
|
||||
if any(
|
||||
not ip_address(address).is_global or ip_address(address).is_multicast
|
||||
for address in (*MAIL_SENDING_IPS, *MAIL_MX_IPS)
|
||||
):
|
||||
raise ImproperlyConfigured(
|
||||
"Set public IP addresses for the mail MX and sending addresses."
|
||||
)
|
||||
MAIL_MX_HOST = os.environ.get("COULOBRE_MAIL_MX_HOST", "").strip()
|
||||
if MAIL_MX_HOST:
|
||||
try:
|
||||
MAIL_MX_HOST = canonical_domain(MAIL_MX_HOST)
|
||||
except ValueError:
|
||||
raise ImproperlyConfigured(
|
||||
"Set a hostname in COULOBRE_MAIL_MX_HOST."
|
||||
) from None
|
||||
MANAGE_MAIL_DNS = os.environ.get("COULOBRE_MANAGE_MAIL_DNS") == "1"
|
||||
if MANAGE_MAIL_DNS and not (MAIL_MX_HOST and MAIL_SENDING_IPS):
|
||||
raise ImproperlyConfigured(
|
||||
"Set COULOBRE_MAIL_MX_HOST and COULOBRE_MAIL_SENDING_IPS "
|
||||
"to provision mail DNS."
|
||||
)
|
||||
PHPMYADMIN_URL = os.environ.get("COULOBRE_PHPMYADMIN_URL", "").rstrip("/")
|
||||
PHPMYADMIN_BRIDGE_KEY = os.environ.get("COULOBRE_PHPMYADMIN_BRIDGE_KEY", "")
|
||||
if PHPMYADMIN_URL:
|
||||
@@ -175,6 +225,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"
|
||||
|
||||
Reference in new issue
Block a user