diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..7263bb2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Report something that isn't working. +title: '' +assignees: '' + +--- + + + +- Server OS (Operating System) - preferably Debian 12: +- On which OS you run cmdeploy: + +## Expected behavior + +*What did you try to achieve?* + +## Actual behavior + +*What happened instead?* + +### Steps to reproduce the problem: + +1. +2. + +### Screenshots + +### Logs + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..f04681f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Mutual Help Chat Group + url: https://i.delta.chat/#C2846EB4C1CB8DF84B1818F5E3A638FC3FBDC981&a=stalebot1%40nine.testrun.org&g=Chatmail%20Mutual%20Help&x=7sFF7Ik50pWv6J1z7RVC5527&i=d7s1HvOsk5UrSf9AoqRZggg4&s=XmX_9BAW6-g5Ao5E8PyaeKNB + about: If you have troubles setting up the relay server, feel free to ask here. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c68ed2..210ee73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,42 @@ ## untagged +- If `dns-utils` needs to be installed before cmdeploy run, apt update to make sure it works + ([#560](https://github.com/chatmail/relay/pull/560)) + +- Add config value after how many days large files are deleted + ([#555](https://github.com/chatmail/relay/pull/555)) + +## 1.6.0 2025-04-11 + +- Handle Port-25 connect errors more gracefully (common with VPNs) + ([#552](https://github.com/chatmail/relay/pull/552)) + +- Avoid "acmetool not found" during initial run + ([#550](https://github.com/chatmail/relay/pull/550)) + +- Fix timezone handling such that client/servers do not need to use + same timezone. + ([#553](https://github.com/chatmail/relay/pull/553)) + +- Enforce end-to-end encryption for incoming messages. + New user address mailboxes now get a `enforceE2EEincoming` file + which prohibits incoming cleartext messages from other domains. + An outside MTA trying to submit a cleartext message will + get a "523 Encryption Needed" response, see RFC5248. + If the file does not exist (as it the case for all existing accounts) + incoming cleartext messages are accepted. + ([#538](https://github.com/chatmail/server/pull/538)) + - Enforce end-to-end encryption between local addresses ([#535](https://github.com/chatmail/server/pull/535)) +- unbound: check that port 53 is not occupied by a different process + ([#537](https://github.com/chatmail/server/pull/537)) + +- unbound: before unbound is there, use 9.9.9.9 for resolving + ([#518](https://github.com/chatmail/relay/pull/518)) + - Limit the bind for the HTTPS server on 8443 to 127.0.0.1 ([#522](https://github.com/chatmail/server/pull/522)) ([#532](https://github.com/chatmail/server/pull/532)) @@ -12,6 +45,9 @@ - Send SNI when connecting to outside servers ([#524](https://github.com/chatmail/server/pull/524)) +- postfix master.cf: use 127.0.0.1 for consistency + ([#544](https://github.com/chatmail/relay/pull/544)) + - Pass through `original_content` instead of `content` in filtermail ([#509](https://github.com/chatmail/server/pull/509)) diff --git a/README-chatmail.md b/README-chatmail.md deleted file mode 100644 index 6da9447..0000000 --- a/README-chatmail.md +++ /dev/null @@ -1,513 +0,0 @@ - - - -# Chatmail servers for secure instant messaging - -Chatmail servers are interoperable email routing machines optimized for: - -- **Convenience:** Low friction instant onboarding - -- **Privacy:** No name, phone numbers, email required or collected -- **Instant:** Privacy-preserving push notifications for Apple, Google, and Huawei - -- **Speed:** Message delivery in well under a second. - -- **Security:** Strict TLS, DKIM and OpenPGP with metadata-minimization rules enforced. - -- **Reliability:** No spam or IP reputation checks, rate-limits suitable for realtime chats. - -- **Efficiency:** Messages are only stored for transit and removed automatically. - -This repository contains everything needed to setup a ready-to-use chatmail server -comprised of a minimal setup of the battle-tested -[Postfix SMTP](https://www.postfix.org) and [Dovecot IMAP](https://www.dovecot.org) services. - -The automated setup is designed and optimized for providing chatmail addresses -for immediate permission-free onboarding through chat apps and bots. -Chatmail addresses are automatically created at first login, -after which the initially specified password is required -for sending and receiving messages through them. - -Please see [this list of known apps and client projects](https://chatmail.at/apps.html) which offer instant onboarding on chatmail servers -and [this list of known public 3rd party chatmail servers](https://chatmail.at/server). - - -## Minimal requirements, Prerequisites - -You will need the following: - -- Control over a domain through a DNS provider of your choice. - -- A Debian 12 server with reachable SMTP/SUBMISSIONS/IMAPS/HTTPS ports. - IPv6 is encouraged if available. - Chatmail servers only require 1GB RAM, one CPU, and perhaps 10GB storage for a - few thousand active chatmail addresses. - -- Key-based SSH authentication to the server's root user. - You must add a passphrase-protected private key to the local ssh-agent - because you can't type in your passphrase during deployment. - (An ed25519 private key is required due to an [upstream bug in paramiko](https://github.com/paramiko/paramiko/issues/2191)) - - -## Getting started - -We use `chat.example.org` as the chatmail domain in the following steps. -Please substitute it with your own domain. - -1. Setup the initial DNS records. - The following is an example in the familiar BIND zone file format with - a TTL of 1 hour (3600 seconds). - Please substitute your domain and IP addresses. - - ``` - chat.example.com. 3600 IN A 198.51.100.5 - chat.example.com. 3600 IN AAAA 2001:db8::5 - www.chat.example.com. 3600 IN CNAME chat.example.com. - mta-sts.chat.example.com. 3600 IN CNAME chat.example.com. - ``` - -2. Clone the repository and bootstrap the Python virtualenv. - - ``` - git clone https://github.com/chatmail/server - cd server - scripts/initenv.sh - ``` - -3. Create chatmail configuration file `chatmail.ini`: - - ``` - scripts/cmdeploy init chat.example.org # <-- use your domain - ``` - -4. Verify that SSH root login works: - - ``` - ssh root@chat.example.org # <-- use your domain - ``` - - -5. Deploy to the remote chatmail server: - - ``` - scripts/cmdeploy run - ``` - This script will check that you have all necessary DNS records. - If DNS records are missing, it will recommend - which you should configure at your DNS provider - (it can take some time until they are public). - -### Other helpful commands: - -To check the status of your remotely running chatmail service: - -``` -scripts/cmdeploy status -``` - -To display and check all recommended DNS records: - -``` -scripts/cmdeploy dns -``` - -To test whether your chatmail service is working correctly: - -``` -scripts/cmdeploy test -``` - -To measure the performance of your chatmail service: - -``` -scripts/cmdeploy bench -``` - -## Overview of this repository - -This repository has four directories: - -- [cmdeploy](https://github.com/chatmail/server/tree/main/cmdeploy) - is a collection of configuration files - and a [pyinfra](https://pyinfra.com)-based deployment script. - -- [chatmaild](https://github.com/chatmail/server/tree/main/chatmaild) - is a Python package containing several small services - which handle authentication, - trigger push notifications on new messages, - ensure that outbound mails are encrypted, - delete inactive users, - and some other minor things. - chatmaild can also be installed as a stand-alone Python package. - -- [www](https://github.com/chatmail/server/tree/main/www) - contains the html, css, and markdown files - which make up a chatmail server's web page. - Edit them before deploying to make your chatmail server stand out. - -- [scripts](https://github.com/chatmail/server/tree/main/scripts) - offers two convenience tools for beginners; - `initenv.sh` installs the necessary dependencies to a local virtual environment, - and the `scripts/cmdeploy` script enables you - to run the `cmdeploy` command line tool in the local virtual environment. - -### cmdeploy - -The `cmdeploy/src/cmdeploy/cmdeploy.py` command line tool -helps with setting up and managing the chatmail service. -`cmdeploy init` creates the `chatmail.ini` config file. -`cmdeploy run` uses a [pyinfra](https://pyinfra.com/)-based [script](`cmdeploy/src/cmdeploy/__init__.py`) -to automatically install or upgrade all chatmail components on a server, -according to the `chatmail.ini` config. - -The components of chatmail are: - -- [Postfix SMTP server](https://www.postfix.org) accepts sent messages (both from your users and from other servers) - -- [Dovecot IMAP server](https://www.dovecot.org) stores messages for your users until they download them - -- [Nginx](https://nginx.org/) shows the web page with your privacy policy and additional information - -- [acmetool](https://hlandau.github.io/acmetool/) manages TLS certificates for Dovecot, Postfix, and Nginx - -- [OpenDKIM](http://www.opendkim.org/) for signing messages with DKIM and rejecting inbound messages without DKIM - -- [mtail](https://google.github.io/mtail/) for collecting anonymized metrics in case you have monitoring - -- and the chatmaild services, explained in the next section: - -### chatmaild - -chatmaild offers several commands -which differentiate a *chatmail* server from a classic mail server. -If you deploy them with cmdeploy, -they are run by systemd services in the background. -A short overview: - -- [`doveauth`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/doveauth.py) implements - create-on-login account creation semantics and is used - by Dovecot during login authentication and by Postfix - which in turn uses [Dovecot SASL](https://doc.dovecot.org/configuration_manual/authentication/dict/#complete-example-for-authenticating-via-a-unix-socket) - to authenticate users - to send mails for them. - -- [`filtermail`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/filtermail.py) prevents - unencrypted email from leaving the chatmail service - and is integrated into Postfix's outbound mail pipelines. - -- [`chatmail-metadata`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/metadata.py) is contacted by a - [dovecot lua script](https://github.com/chatmail/server/blob/main/cmdeploy/src/cmdeploy/dovecot/push_notification.lua) - to store user-specific server-side config. - On new messages, - it [passes the user's push notification token](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/notifier.py) - to [notifications.delta.chat](https://delta.chat/help#instant-delivery) - so the push notifications on the user's phone can be triggered - by Apple/Google/Huawei. - -- [`delete_inactive_users`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/delete_inactive_users.py) - deletes users if they have not logged in for a very long time. - The timeframe can be configured in `chatmail.ini`. - -- [`lastlogin`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/lastlogin.py) - is contacted by dovecot when a user logs in - and stores the date of the login. - -- [`echobot`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/echo.py) - is a small bot for test purposes. - It simply echoes back messages from users. - -- [`chatmail-metrics`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/metrics.py) - collects some metrics and displays them at `https://example.org/metrics`. - -### Home page and getting started for users - -`cmdeploy run` also creates default static web pages and deploys them -to a Nginx web server with: - -- a default `index.html` along with a QR code that users can click to - create accounts on your chatmail provider - -- a default `info.html` that is linked from the home page - -- a default `policy.html` that is linked from the home page - -All `.html` files are generated -by the according markdown `.md` file in the `www/src` directory. - - -### Refining the web pages - - -``` -scripts/cmdeploy webdev -``` - -This starts a local live development cycle for chatmail web pages: - -- uses the `www/src/page-layout.html` file for producing static - HTML pages from `www/src/*.md` files - -- continously builds the web presence reading files from `www/src` directory - and generating HTML files and copying assets to the `www/build` directory. - -- Starts a browser window automatically where you can "refresh" as needed. - - -## Emergency Commands to disable automatic account creation - -If you need to stop account creation, -e.g. because some script is wildly creating accounts, -login to the server with ssh and run: - -``` - touch /etc/chatmail-nocreate -``` - -Account creation will be denied while this file is present. - -### Ports - -[Postfix](http://www.postfix.org/) listens on ports 25 (SMTP) and 587 (SUBMISSION) and 465 (SUBMISSIONS). -[Dovecot](https://www.dovecot.org/) listens on ports 143 (IMAP) and 993 (IMAPS). -[Nginx](https://www.nginx.com/) listens on port 8443 (HTTPS-ALT) and 443 (HTTPS). -Port 443 multiplexes HTTPS, IMAP and SMTP using ALPN to redirect connections to ports 8443, 465 or 993. -[acmetool](https://hlandau.github.io/acmetool/) listens on port 80 (HTTP). - -chatmail-core based apps will, however, discover all ports and configurations -automatically by reading the [autoconfig XML file](https://www.ietf.org/archive/id/draft-bucksch-autoconfig-00.html) from the chatmail server. - -## Email authentication - -chatmail servers rely on [DKIM](https://www.rfc-editor.org/rfc/rfc6376) -to authenticate incoming emails. -Incoming emails must have a valid DKIM signature with -Signing Domain Identifier (SDID, `d=` parameter in the DKIM-Signature header) -equal to the `From:` header domain. -This property is checked by OpenDKIM screen policy script -before validating the signatures. -This correpsonds to strict [DMARC](https://www.rfc-editor.org/rfc/rfc7489) alignment (`adkim=s`), -but chatmail does not rely on DMARC and does not consult the sender policy published in DMARC records. -Other legacy authentication mechanisms such as [iprev](https://www.rfc-editor.org/rfc/rfc8601#section-2.7.3) -and [SPF](https://www.rfc-editor.org/rfc/rfc7208) are also not taken into account. -If there is no valid DKIM signature on the incoming email, -the sender receives a "5.7.1 No valid DKIM signature found" error. - -Outgoing emails must be sent over authenticated connection -with envelope MAIL FROM (return path) corresponding to the login. -This is ensured by Postfix which maps login username -to MAIL FROM with -[`smtpd_sender_login_maps`](https://www.postfix.org/postconf.5.html#smtpd_sender_login_maps) -and rejects incorrectly authenticated emails with [`reject_sender_login_mismatch`](reject_sender_login_mismatch) policy. -`From:` header must correspond to envelope MAIL FROM, -this is ensured by `filtermail` proxy. - -## TLS requirements - -Postfix is configured to require valid TLS -by setting [`smtp_tls_security_level`](https://www.postfix.org/postconf.5.html#smtp_tls_security_level) to `verify`. -If emails don't arrive from a chatmail server to your server, -the problem is likely that your server does not have a valid TLS certificate. - -You can test it by resolving `MX` records of your server domain -and then connecting to MX servers (e.g `mx.example.org`) with -`openssl s_client -connect mx.example.org:25 -verify_hostname mx.example.org -verify_return_error -starttls smtp` -from the host that has open port 25 to verify that certificate is valid. - -When providing a TLS certificate to your server, -make sure to provide the full certificate chain -and not just the last certificate. - -If you are running Exim server and don't see incoming connections -from a chatmail server in the logs, -make sure `smtp_no_mail` log item is enabled in the config -with `log_selector = +smtp_no_mail`. -By default Exim does not log sessions that are closed -before sending the `MAIL` command. -This happens if certificate is not recognized as valid by Postfix, -so you might think that connection is not established -while actually it is a problem with your TLS certificate. - -## Migrating chatmail server to a new host - -If you want to migrate chatmail from an old machine -to a new machine, -you can use these steps. -They were tested with a Linux laptop; -you might need to adjust some of the steps to your environment. - -Let's assume that your `mail_domain` is `mail.example.org`, -all involved machines run Debian 12, -your old server's IP address is `13.37.13.37`, -and your new server's IP address is `13.12.23.42`. - -Note, you should lower the TTLs of your DNS records to a value -such as 300 (5 minutes) so the migration happens as smoothly as possible. - -During the guide you might get a warning about changed SSH Host keys; -in this case, just run `ssh-keygen -R "mail.example.org"` as recommended. - -1. First, disable mail services on the old server. - - ``` - cmdeploy run --disable-mail --ssh-host 13.37.13.37 - ``` - - Now your users will notice the migration - and will not be able to send or receive messages - until the migration is completed. - -2. Now we want to copy `/home/vmail`, `/var/lib/acme`, `/etc/dkimkeys`, `/run/echobot`, and `/var/spool/postfix` to the new server. - Login to the old server while forwarding your SSH agent so you can copy directly from the old server to the new server with - your SSH key: - - ``` - ssh -A root@13.37.13.37 - tar c - /home/vmail/mail /var/lib/acme /etc/dkimkeys /run/echobot /var/spool/postfix | ssh root@13.12.23.42 "tar x -C /" - ``` - - This transfers all accounts, the TLS certificate, DKIM keys (so DKIM DNS record remains valid), and the echobot's password so it continues to function. - It also preserves the Postfix mail spool so any messages pending delivery will still be delivered. - -3. Install chatmail on the new machine: - - ``` - cmdeploy run --disable-mail --ssh-host 13.12.23.42 - ``` - Postfix and Dovecot are disabled for now; we will enable them later. This ensures all user accounts are provisioned. - -3. On the new server, run the following to ensure the ownership is correct in case UIDs/GIDs changed: - - ``` - chown root: -R /var/lib/acme - chown opendkim: -R /etc/dkimkeys - chown vmail: -R /home/vmail/mail - chown echobot: -R /run/echobot - ``` - -4. Now, update DNS to the new IP addresses. - - If other servers try to deliver messages to your server they may fail, - but normally email servers will retry delivering messages - for at least a week, so messages will not be lost. - -5. Finally, you can execute `cmdeploy run --ssh-host 13.12.23.42` to turn on chatmail on the new server. - Your users will be able to use the chatmail server as soon as the DNS changes have propagated. - VoilĂ ! - -## Setting up a reverse proxy - -A chatmail server does not depend on the client IP address -for its operation, so it can be run behind a reverse proxy. -This will not even affect incoming mail authentication -as DKIM only checks the cryptographic signature -of the message and does not use the IP address as the input. - -For example, you may want to self-host your chatmail server -and only use hosted VPS to provide a public IP address -for client connections and incoming mail. -You can connect chatmail server to VPS -using a tunnel protocol -such as [WireGuard](https://www.wireguard.com/) -and setup a reverse proxy on a VPS -to forward connections to the chatmail server -over the tunnel. -You can also setup multiple reverse proxies -for your chatmail server in different networks -to ensure your server is reachable even when -one of the IPs becomes inaccessible due to -hosting or routing problems. - -Note that your server still needs -to be able to make outgoing connections on port 25 -to send messages outside. - -To setup a reverse proxy -(or rather Destination NAT, DNAT) -for your chatmail server, -put the following configuration in `/etc/nftables.conf`: -``` -#!/usr/sbin/nft -f - -flush ruleset - -define wan = eth0 - -# Which ports to proxy. -# -# Note that SSH is not proxied -# so it is possible to log into the proxy server -# and not the original one. -define ports = { smtp, http, https, imap, imaps, submission, submissions } - -# The host we want to proxy to. -define ipv4_address = AAA.BBB.CCC.DDD -define ipv6_address = [XXX::1] - -table ip nat { - chain prerouting { - type nat hook prerouting priority dstnat; policy accept; - iif $wan tcp dport $ports dnat to $ipv4_address - } - - chain postrouting { - type nat hook postrouting priority 0; - - oifname $wan masquerade - } -} - -table ip6 nat { - chain prerouting { - type nat hook prerouting priority dstnat; policy accept; - iif $wan tcp dport $ports dnat to $ipv6_address - } - - chain postrouting { - type nat hook postrouting priority 0; - - oifname $wan masquerade - } -} - -table inet filter { - chain input { - type filter hook input priority filter; policy drop; - - # Accept ICMP. - # It is especially important to accept ICMPv6 ND messages, - # otherwise IPv6 connectivity breaks. - icmp type { echo-request } accept - icmpv6 type { echo-request, nd-neighbor-solicit, nd-router-advert, nd-neighbor-advert } accept - - # Allow incoming SSH connections. - tcp dport { ssh } accept - - ct state established accept - } - chain forward { - type filter hook forward priority filter; policy drop; - - ct state established accept - ip daddr $ipv4_address counter accept - ip6 daddr $ipv6_address counter accept - } - chain output { - type filter hook output priority filter; - } -} -``` - -Run `systemctl enable nftables.service` -to ensure configuration is reloaded when the proxy server reboots. - -Uncomment in `/etc/sysctl.conf` the following two lines: - -``` -net.ipv4.ip_forward=1 -net.ipv6.conf.all.forwarding=1 -``` - -Then reboot the server or do `sysctl -p` and `nft -f /etc/nftables.conf`. - -Once proxy server is set up, -you can add its IP address to the DNS. diff --git a/README.md b/README.md index 31fa006..ce0c270 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,551 @@ - # arcanechat.me server arcanechat.me is a [chatmail](https://github.com/deltachat/chatmail) server deployment for the ArcaneChat app. + +
+ + + +# Chatmail relays for end-to-end encrypted e-mail + +Chatmail relay servers are interoperable Mail Transport Agents (MTAs) designed for: + +- **Convenience:** Low friction instant onboarding + +- **Privacy:** No name, phone numbers, email required or collected + +- **End-to-End Encryption enforced**: only OpenPGP messages with metadata minimization allowed + +- **Instant:** Privacy-preserving Push Notifications for Apple, Google, and Huawei + +- **Speed:** Message delivery in half a second, with optional P2P realtime connections + +- **Transport Security:** Strict TLS and DKIM enforced + +- **Reliability:** No spam or IP reputation checks; rate-limits are suitable for realtime chats + +- **Efficiency:** Messages are only stored for transit and removed automatically + +This repository contains everything needed to setup a ready-to-use chatmail relay +comprised of a minimal setup of the battle-tested +[Postfix SMTP](https://www.postfix.org) and [Dovecot IMAP](https://www.dovecot.org) MTAs/MDAs. + +The automated setup is designed and optimized for providing chatmail addresses +for immediate permission-free onboarding through chat apps and bots. +Chatmail addresses are automatically created at first login, +after which the initially specified password is required +for sending and receiving messages through them. + +Please see [this list of known apps and client projects](https://chatmail.at/clients.html) +and [this list of known public 3rd party chatmail relay servers](https://chatmail.at/relays). + + +## Minimal requirements, Prerequisites + +You will need the following: + +- Control over a domain through a DNS provider of your choice. + +- A Debian 12 server with reachable SMTP/SUBMISSIONS/IMAPS/HTTPS ports. + IPv6 is encouraged if available. + Chatmail relay servers only require 1GB RAM, one CPU, and perhaps 10GB storage for a + few thousand active chatmail addresses. + +- Key-based SSH authentication to the root user. + You must add a passphrase-protected private key to your local ssh-agent + because you can't type in your passphrase during deployment. + (An ed25519 private key is required due to an [upstream bug in paramiko](https://github.com/paramiko/paramiko/issues/2191)) + + +## Getting started + +We use `chat.example.org` as the chatmail domain in the following steps. +Please substitute it with your own domain. + +1. Setup the initial DNS records. + The following is an example in the familiar BIND zone file format with + a TTL of 1 hour (3600 seconds). + Please substitute your domain and IP addresses. + + ``` + chat.example.com. 3600 IN A 198.51.100.5 + chat.example.com. 3600 IN AAAA 2001:db8::5 + www.chat.example.com. 3600 IN CNAME chat.example.com. + mta-sts.chat.example.com. 3600 IN CNAME chat.example.com. + ``` + +2. Clone the repository and bootstrap the Python virtualenv. + + ``` + git clone https://github.com/chatmail/relay + cd relay + scripts/initenv.sh + ``` + +3. Create chatmail configuration file `chatmail.ini`: + + ``` + scripts/cmdeploy init chat.example.org # <-- use your domain + ``` + +4. Verify that SSH root login works: + + ``` + ssh root@chat.example.org # <-- use your domain + ``` + + +5. Deploy the remote chatmail relay server: + + ``` + scripts/cmdeploy run + ``` + This script will check that you have all necessary DNS records. + If DNS records are missing, it will recommend + which you should configure at your DNS provider + (it can take some time until they are public). + +### Other helpful commands: + +To check the status of your remotely running chatmail service: + +``` +scripts/cmdeploy status +``` + +To display and check all recommended DNS records: + +``` +scripts/cmdeploy dns +``` + +To test whether your chatmail service is working correctly: + +``` +scripts/cmdeploy test +``` + +To measure the performance of your chatmail service: + +``` +scripts/cmdeploy bench +``` + +## Overview of this repository + +This repository has four directories: + +- [cmdeploy](https://github.com/chatmail/relay/tree/main/cmdeploy) + is a collection of configuration files + and a [pyinfra](https://pyinfra.com)-based deployment script. + +- [chatmaild](https://github.com/chatmail/relay/tree/main/chatmaild) + is a Python package containing several small services + which handle authentication, + trigger push notifications on new messages, + ensure that outbound mails are encrypted, + delete inactive users, + and some other minor things. + chatmaild can also be installed as a stand-alone Python package. + +- [www](https://github.com/chatmail/relay/tree/main/www) + contains the html, css, and markdown files + which make up a chatmail relay's web page. + Edit them before deploying to make your chatmail relay stand out. + +- [scripts](https://github.com/chatmail/relay/tree/main/scripts) + offers two convenience tools for beginners; + `initenv.sh` installs the necessary dependencies to a local virtual environment, + and the `scripts/cmdeploy` script enables you + to run the `cmdeploy` command line tool in the local virtual environment. + +### cmdeploy + +The `cmdeploy/src/cmdeploy/cmdeploy.py` command line tool +helps with setting up and managing the chatmail service. +`cmdeploy init` creates the `chatmail.ini` config file. +`cmdeploy run` uses a [pyinfra](https://pyinfra.com/)-based [`script`](cmdeploy/src/cmdeploy/__init__.py) +to automatically install or upgrade all chatmail components on a relay, +according to the `chatmail.ini` config. + +The components of chatmail are: + +- [Postfix SMTP MTA](https://www.postfix.org) accepts and relays messages + (both from your users and from the wider e-mail MTA network) + +- [Dovecot IMAP MDA](https://www.dovecot.org) stores messages for your users until they download them + +- [Nginx](https://nginx.org/) shows the web page with your privacy policy and additional information + +- [acmetool](https://hlandau.github.io/acmetool/) manages TLS certificates for Dovecot, Postfix, and Nginx + +- [OpenDKIM](http://www.opendkim.org/) for signing messages with DKIM and rejecting inbound messages without DKIM + +- [mtail](https://google.github.io/mtail/) for collecting anonymized metrics in case you have monitoring + +- [Iroh relay](https://www.iroh.computer/docs/concepts/relay) + which helps client devices to establish Peer-to-Peer connections + +- and the chatmaild services, explained in the next section: + +### chatmaild + +`chatmaild` implements various systemd-controlled services +that integrate with Dovecot and Postfix to achieve instant-onboarding and +only relaying OpenPGP end-to-end messages encrypted messages. +A short overview of `chatmaild` services: + +- [`doveauth`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/doveauth.py) + implements create-on-login address semantics and is used + by Dovecot during IMAP login and by Postfix during SMTP/SUBMISSION login + which in turn uses [Dovecot SASL](https://doc.dovecot.org/configuration_manual/authentication/dict/#complete-example-for-authenticating-via-a-unix-socket) + to authenticate logins. + +- [`filtermail`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/filtermail.py) + prevents unencrypted email from leaving or entering the chatmail service + and is integrated into Postfix's outbound and inbound mail pipelines. + +- [`chatmail-metadata`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/metadata.py) is contacted by a + [Dovecot lua script](https://github.com/chatmail/relay/blob/main/cmdeploy/src/cmdeploy/dovecot/push_notification.lua) + to store user-specific relay-side config. + On new messages, + it [passes the user's push notification token](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/notifier.py) + to [notifications.delta.chat](https://delta.chat/help#instant-delivery) + so the push notifications on the user's phone can be triggered + by Apple/Google/Huawei. + +- [`delete_inactive_users`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/delete_inactive_users.py) + deletes users if they have not logged in for a very long time. + The timeframe can be configured in `chatmail.ini`. + +- [`lastlogin`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/lastlogin.py) + is contacted by Dovecot when a user logs in + and stores the date of the login. + +- [`echobot`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/echo.py) + is a small bot for test purposes. + It simply echoes back messages from users. + +- [`chatmail-metrics`](https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/metrics.py) + collects some metrics and displays them at `https://example.org/metrics`. + +### Home page and getting started for users + +`cmdeploy run` also creates default static web pages and deploys them +to a Nginx web server with: + +- a default `index.html` along with a QR code that users can click to + create an address on your chatmail relay + +- a default `info.html` that is linked from the home page + +- a default `policy.html` that is linked from the home page + +All `.html` files are generated +by the according markdown `.md` file in the `www/src` directory. + + +### Refining the web pages + +``` +scripts/cmdeploy webdev +``` + +This starts a local live development cycle for chatmail web pages: + +- uses the `www/src/page-layout.html` file for producing static + HTML pages from `www/src/*.md` files + +- continously builds the web presence reading files from `www/src` directory + and generating HTML files and copying assets to the `www/build` directory. + +- Starts a browser window automatically where you can "refresh" as needed. + +## Mailbox directory layout + +Fresh chatmail addresses have a mailbox directory that contains: + +- a `password` file with the salted password required for authenticating + whether a login may use the address to send/receive messages. + If you modify the password file manually, you effectively block the user. + +- `enforceE2EEincoming` is a default-created file with each address. + If present the file indicates that this chatmail address rejects incoming cleartext messages. + If absent the address accepts incoming cleartext messages. + +- `dovecot*`, `cur`, `new` and `tmp` represent IMAP/mailbox state. + If the address is only used by one device, the Maildir directories + will typically be empty unless the user of that address hasn't been online + for a while. + + +## Emergency Commands to disable automatic address creation + +If you need to stop address creation, +e.g. because some script is wildly creating addresses, +login with ssh and run: + +``` + touch /etc/chatmail-nocreate +``` + +Chatmail address creation will be denied while this file is present. + +### Ports + +[Postfix](http://www.postfix.org/) listens on ports 25 (SMTP) and 587 (SUBMISSION) and 465 (SUBMISSIONS). +[Dovecot](https://www.dovecot.org/) listens on ports 143 (IMAP) and 993 (IMAPS). +[Nginx](https://www.nginx.com/) listens on port 8443 (HTTPS-ALT) and 443 (HTTPS). +Port 443 multiplexes HTTPS, IMAP and SMTP using ALPN to redirect connections to ports 8443, 465 or 993. +[acmetool](https://hlandau.github.io/acmetool/) listens on port 80 (HTTP). + +chatmail-core based apps will, however, discover all ports and configurations +automatically by reading the [autoconfig XML file](https://www.ietf.org/archive/id/draft-bucksch-autoconfig-00.html) from the chatmail relay server. + +## Email authentication + +Chatmail relays enforce [DKIM](https://www.rfc-editor.org/rfc/rfc6376) +to authenticate incoming emails. +Incoming emails must have a valid DKIM signature with +Signing Domain Identifier (SDID, `d=` parameter in the DKIM-Signature header) +equal to the `From:` header domain. +This property is checked by OpenDKIM screen policy script +before validating the signatures. +This correpsonds to strict [DMARC](https://www.rfc-editor.org/rfc/rfc7489) alignment (`adkim=s`), +but chatmail does not rely on DMARC and does not consult the sender policy published in DMARC records. +Other legacy authentication mechanisms such as [iprev](https://www.rfc-editor.org/rfc/rfc8601#section-2.7.3) +and [SPF](https://www.rfc-editor.org/rfc/rfc7208) are also not taken into account. +If there is no valid DKIM signature on the incoming email, +the sender receives a "5.7.1 No valid DKIM signature found" error. + +Outgoing emails must be sent over authenticated connection +with envelope MAIL FROM (return path) corresponding to the login. +This is ensured by Postfix which maps login username +to MAIL FROM with +[`smtpd_sender_login_maps`](https://www.postfix.org/postconf.5.html#smtpd_sender_login_maps) +and rejects incorrectly authenticated emails with [`reject_sender_login_mismatch`](reject_sender_login_mismatch) policy. +`From:` header must correspond to envelope MAIL FROM, +this is ensured by `filtermail` proxy. + +## TLS requirements + +Postfix is configured to require valid TLS +by setting [`smtp_tls_security_level`](https://www.postfix.org/postconf.5.html#smtp_tls_security_level) to `verify`. +If emails don't arrive at your chatmail relay server, +the problem is likely that your relay does not have a valid TLS certificate. + +You can test it by resolving `MX` records of your relay domain +and then connecting to MX relays (e.g `mx.example.org`) with +`openssl s_client -connect mx.example.org:25 -verify_hostname mx.example.org -verify_return_error -starttls smtp` +from the host that has open port 25 to verify that certificate is valid. + +When providing a TLS certificate to your chatmail relay server, +make sure to provide the full certificate chain +and not just the last certificate. + +If you are running an Exim server and don't see incoming connections +from a chatmail relay server in the logs, +make sure `smtp_no_mail` log item is enabled in the config +with `log_selector = +smtp_no_mail`. +By default Exim does not log sessions that are closed +before sending the `MAIL` command. +This happens if certificate is not recognized as valid by Postfix, +so you might think that connection is not established +while actually it is a problem with your TLS certificate. + +## Migrating a chatmail relay to a new host + +If you want to migrate chatmail relay from an old machine +to a new machine, +you can use these steps. +They were tested with a Linux laptop; +you might need to adjust some of the steps to your environment. + +Let's assume that your `mail_domain` is `mail.example.org`, +all involved machines run Debian 12, +your old site's IP address is `13.37.13.37`, +and your new site's IP address is `13.12.23.42`. + +Note, you should lower the TTLs of your DNS records to a value +such as 300 (5 minutes) so the migration happens as smoothly as possible. + +During the guide you might get a warning about changed SSH Host keys; +in this case, just run `ssh-keygen -R "mail.example.org"` as recommended. + +1. First, disable mail services on the old site. + + ``` + cmdeploy run --disable-mail --ssh-host 13.37.13.37 + ``` + + Now your users will notice the migration + and will not be able to send or receive messages + until the migration is completed. + +2. Now we want to copy `/home/vmail`, `/var/lib/acme`, `/etc/dkimkeys`, `/run/echobot`, and `/var/spool/postfix` to the new site. + Login to the old site while forwarding your SSH agent + so you can copy directly from the old to the new site with your SSH key: + ``` + ssh -A root@13.37.13.37 + tar c - /home/vmail/mail /var/lib/acme /etc/dkimkeys /run/echobot /var/spool/postfix | ssh root@13.12.23.42 "tar x -C /" + ``` + + This transfers all addresses, the TLS certificate, DKIM keys (so DKIM DNS record remains valid), and the echobot's password so it continues to function. + It also preserves the Postfix mail spool so any messages pending delivery will still be delivered. + +3. Install chatmail on the new machine: + + ``` + cmdeploy run --disable-mail --ssh-host 13.12.23.42 + ``` + Postfix and Dovecot are disabled for now; we will enable them later. + We first need to make the new site fully operational. + +3. On the new site, run the following to ensure the ownership is correct in case UIDs/GIDs changed: + + ``` + chown root: -R /var/lib/acme + chown opendkim: -R /etc/dkimkeys + chown vmail: -R /home/vmail/mail + chown echobot: -R /run/echobot + ``` + +4. Now, update DNS entries. + + If other MTAs try to deliver messages to your chatmail domain they may fail intermittently, + as DNS catches up with the new site settings + but normally will retry delivering messages + for at least a week, so messages will not be lost. + +5. Finally, you can execute `cmdeploy run --ssh-host 13.12.23.42` to turn on chatmail on the new relay. + Your users will be able to use the chatmail relay as soon as the DNS changes have propagated. + VoilĂ ! + +## Setting up a reverse proxy + +A chatmail relay MTA does not track or depend on the client IP address +for its operation, so it can be run behind a reverse proxy. +This will not even affect incoming mail authentication +as DKIM only checks the cryptographic signature +of the message and does not use the IP address as the input. + +For example, you may want to self-host your chatmail relay +and only use hosted VPS to provide a public IP address +for client connections and incoming mail. +You can connect chatmail relay to VPS +using a tunnel protocol +such as [WireGuard](https://www.wireguard.com/) +and setup a reverse proxy on a VPS +to forward connections to the chatmail relay +over the tunnel. +You can also setup multiple reverse proxies +for your chatmail relay in different networks +to ensure your relay is reachable even when +one of the IPs becomes inaccessible due to +hosting or routing problems. + +Note that your chatmail relay still needs +to be able to make outgoing connections on port 25 +to send messages outside. + +To setup a reverse proxy +(or rather Destination NAT, DNAT) +for your chatmail relay, +put the following configuration in `/etc/nftables.conf`: +``` +#!/usr/sbin/nft -f + +flush ruleset + +define wan = eth0 + +# Which ports to proxy. +# +# Note that SSH is not proxied +# so it is possible to log into the proxy server +# and not the original one. +define ports = { smtp, http, https, imap, imaps, submission, submissions } + +# The host we want to proxy to. +define ipv4_address = AAA.BBB.CCC.DDD +define ipv6_address = [XXX::1] + +table ip nat { + chain prerouting { + type nat hook prerouting priority dstnat; policy accept; + iif $wan tcp dport $ports dnat to $ipv4_address + } + + chain postrouting { + type nat hook postrouting priority 0; + + oifname $wan masquerade + } +} + +table ip6 nat { + chain prerouting { + type nat hook prerouting priority dstnat; policy accept; + iif $wan tcp dport $ports dnat to $ipv6_address + } + + chain postrouting { + type nat hook postrouting priority 0; + + oifname $wan masquerade + } +} + +table inet filter { + chain input { + type filter hook input priority filter; policy drop; + + # Accept ICMP. + # It is especially important to accept ICMPv6 ND messages, + # otherwise IPv6 connectivity breaks. + icmp type { echo-request } accept + icmpv6 type { echo-request, nd-neighbor-solicit, nd-router-advert, nd-neighbor-advert } accept + + # Allow incoming SSH connections. + tcp dport { ssh } accept + + ct state established accept + } + chain forward { + type filter hook forward priority filter; policy drop; + + ct state established accept + ip daddr $ipv4_address counter accept + ip6 daddr $ipv6_address counter accept + } + chain output { + type filter hook output priority filter; + } +} +``` + +Run `systemctl enable nftables.service` +to ensure configuration is reloaded when the proxy relay reboots. + +Uncomment in `/etc/sysctl.conf` the following two lines: + +``` +net.ipv4.ip_forward=1 +net.ipv6.conf.all.forwarding=1 +``` + +Then reboot the relay or do `sysctl -p` and `nft -f /etc/nftables.conf`. + +Once proxy relay is set up, +you can add its IP address to the DNS. + +## Neighbors and Acquaintances + +Here are some related projects that you may be interested in: + +- [Mox](https://github.com/mjl-/mox): A Golang email server. [Work is in + progress](https://github.com/mjl-/mox/issues/251) to modify it to support all + of the features and configuration settings required to operate as a chatmail + relay. diff --git a/chatmaild/src/chatmaild/aiosmtpd_patch.py b/chatmaild/src/chatmaild/aiosmtpd_patch.py deleted file mode 100644 index c12606b..0000000 --- a/chatmaild/src/chatmaild/aiosmtpd_patch.py +++ /dev/null @@ -1,143 +0,0 @@ -import logging -from typing import Optional - -from aiosmtpd.controller import Controller -from aiosmtpd.smtp import MISSING, SMTP, syntax - -log = logging.getLogger("mail.log") - - -class PatchedController(Controller): - def factory(self): - """Subclasses can override this to customize the handler/server creation.""" - return PatchedSMTP(self.handler, **self.SMTP_kwargs) - - -class PatchedSMTP(SMTP): - @syntax("MAIL FROM:
", extended=" [SP ]") - async def smtp_MAIL(self, arg: Optional[str]) -> None: - if await self.check_helo_needed(): - return - if await self.check_auth_needed("MAIL"): - return - syntaxerr = "501 Syntax: MAIL FROM:
" - assert self.session is not None - if self.session.extended_smtp: - syntaxerr += " [SP ]" - if arg is None: - await self.push(syntaxerr) - return - arg = self._strip_command_keyword("FROM:", arg) - if arg is None: - await self.push(syntaxerr) - return - address, addrparams = self._getaddr(arg) - if address is None: - await self.push("553 5.1.3 Error: malformed address") - return - if not address: - await self.push(syntaxerr) - return - if not self.session.extended_smtp and addrparams: - await self.push(syntaxerr) - return - assert self.envelope is not None - if self.envelope.mail_from: - await self.push("503 Error: nested MAIL command") - return - assert addrparams is not None - mail_options = addrparams.upper().split() - params = self._getparams(mail_options) - if params is None: - await self.push(syntaxerr) - return - if not self._decode_data: - body = params.pop("BODY", "7BIT") - if body not in ["7BIT", "8BITMIME"]: - await self.push("501 Error: BODY can only be one of 7BIT, 8BITMIME") - return - smtputf8 = params.pop("SMTPUTF8", False) - if not isinstance(smtputf8, bool): - await self.push("501 Error: SMTPUTF8 takes no arguments") - return - if smtputf8 and not self.enable_SMTPUTF8: - await self.push("501 Error: SMTPUTF8 disabled") - return - self.envelope.smtp_utf8 = smtputf8 - size = params.pop("SIZE", None) - if size: - if isinstance(size, bool) or not size.isdigit(): - await self.push(syntaxerr) - return - elif self.data_size_limit and int(size) > self.data_size_limit: - await self.push( - "552 Error: message size exceeds fixed maximum message " "size" - ) - return - """ - if len(params) > 0: - await self.push( - '555 MAIL FROM parameters not recognized or not implemented') - return - """ - status = await self._call_handler_hook("MAIL", address, mail_options) - if status is MISSING: - self.envelope.mail_from = address - self.envelope.mail_options.extend(mail_options) - status = "250 OK" - log.info("%r sender: %s", self.session.peer, address) - await self.push(status) - - @syntax("RCPT TO:
", extended=" [SP ]") - async def smtp_RCPT(self, arg: Optional[str]) -> None: - if await self.check_helo_needed(): - return - if await self.check_auth_needed("RCPT"): - return - assert self.envelope is not None - if not self.envelope.mail_from: - await self.push("503 Error: need MAIL command") - return - - syntaxerr = "501 Syntax: RCPT TO:
" - assert self.session is not None - if self.session.extended_smtp: - syntaxerr += " [SP ]" - if arg is None: - await self.push(syntaxerr) - return - arg = self._strip_command_keyword("TO:", arg) - if arg is None: - await self.push(syntaxerr) - return - address, params = self._getaddr(arg) - if address is None: - await self.push("553 5.1.3 Error: malformed address") - return - if not address: - await self.push(syntaxerr) - return - if not self.session.extended_smtp and params: - await self.push(syntaxerr) - return - assert params is not None - rcpt_options = params.upper().split() - params_dict = self._getparams(rcpt_options) - if params_dict is None: - await self.push(syntaxerr) - return - # XXX currently there are no options we recognize. - """ - if len(params_dict) > 0: - await self.push( - '555 RCPT TO parameters not recognized or not implemented' - ) - return - """ - status = await self._call_handler_hook("RCPT", address, rcpt_options) - if status is MISSING: - self.envelope.rcpt_tos.append(address) - self.envelope.rcpt_options.extend(rcpt_options) - status = "250 OK" - log.info("%r recip: %s", self.session.peer, address) - await self.push(status) diff --git a/chatmaild/src/chatmaild/config.py b/chatmaild/src/chatmaild/config.py index 346399d..971906b 100644 --- a/chatmaild/src/chatmaild/config.py +++ b/chatmaild/src/chatmaild/config.py @@ -11,7 +11,11 @@ def read_config(inipath): assert Path(inipath).exists(), inipath cfg = iniconfig.IniConfig(inipath) params = cfg.sections["params"] - return Config(inipath, params=params) + default_config_content = get_default_config_content(params["mail_domain"]) + df_params = iniconfig.IniConfig("ini", data=default_config_content)["params"] + new_params = dict(df_params.items()) + new_params.update(params) + return Config(inipath, params=new_params) class Config: @@ -22,6 +26,7 @@ class Config: self.max_mailbox_size = params["max_mailbox_size"] self.max_message_size = int(params.get("max_message_size", "31457280")) self.delete_mails_after = params["delete_mails_after"] + self.delete_large_after = params["delete_large_after"] self.delete_inactive_users_after = int(params["delete_inactive_users_after"]) self.username_min_length = int(params["username_min_length"]) self.username_max_length = int(params["username_max_length"]) @@ -29,12 +34,12 @@ class Config: self.passthrough_senders = params["passthrough_senders"].split() self.passthrough_recipients = params["passthrough_recipients"].split() self.filtermail_smtp_port = int(params["filtermail_smtp_port"]) - self.filtermail_incoming_smtp_port = int( - params.get("filtermail_incoming_smtp_port", "10081") + self.filtermail_smtp_port_incoming = int( + params["filtermail_smtp_port_incoming"] ) self.postfix_reinject_port = int(params["postfix_reinject_port"]) - self.postfix_incoming_reinject_port = int( - params.get("postfix_incoming_reinject_port", "10026") + self.postfix_reinject_port_incoming = int( + params["postfix_reinject_port_incoming"] ) self.mtail_address = params.get("mtail_address") self.disable_ipv6 = params.get("disable_ipv6", "false").lower() == "true" @@ -75,6 +80,11 @@ class Config: def write_initial_config(inipath, mail_domain, overrides): """Write out default config file, using the specified config value overrides.""" + content = get_default_config_content(mail_domain, **overrides) + inipath.write_text(content) + + +def get_default_config_content(mail_domain, **overrides): from importlib.resources import files inidir = files(__package__).joinpath("ini") @@ -119,5 +129,4 @@ def write_initial_config(inipath, mail_domain, overrides): else: lines.append(line) content = "\n".join(lines) - - inipath.write_text(content) + return content diff --git a/chatmaild/src/chatmaild/filtermail.py b/chatmaild/src/chatmaild/filtermail.py index eb62484..f66188e 100644 --- a/chatmaild/src/chatmaild/filtermail.py +++ b/chatmaild/src/chatmaild/filtermail.py @@ -10,9 +10,13 @@ from email.parser import BytesParser from email.utils import parseaddr from smtplib import SMTP as SMTPClient -from .aiosmtpd_patch import PatchedController as Controller +from aiosmtpd.controller import Controller +from aiosmtpd.smtp import SMTP + from .config import read_config +ENCRYPTION_NEEDED_523 = "523 Encryption Needed: Invalid Unencrypted Mail" + def check_openpgp_payload(payload: bytes): """Checks the OpenPGP payload. @@ -156,11 +160,14 @@ def check_encrypted(message): return True -async def asyncmain_beforequeue(config): - port = config.filtermail_smtp_port - port2 = config.filtermail_incoming_smtp_port - Controller(BeforeQueueHandler(config), hostname="127.0.0.1", port=port).start() - Controller(IncomingMsgsHandler(config), hostname="127.0.0.1", port=port2).start() +async def asyncmain_beforequeue(config, mode): + if mode == "outgoing": + port = config.filtermail_smtp_port + handler = OutgoingBeforeQueueHandler(config) + else: + port = config.filtermail_smtp_port_incoming + handler = IncomingBeforeQueueHandler(config) + HackedController(handler, hostname="127.0.0.1", port=port).start() def recipient_matches_passthrough(recipient, passthrough_recipients): @@ -172,7 +179,21 @@ def recipient_matches_passthrough(recipient, passthrough_recipients): return False -class BeforeQueueHandler: +class HackedController(Controller): + def factory(self): + return SMTPDiscardRCPTO_options(self.handler, **self.SMTP_kwargs) + + +class SMTPDiscardRCPTO_options(SMTP): + def _getparams(self, params): + # aiosmtpd's SMTP daemon fails to handle a request if there are RCPT TO options + # We just ignore them for our incoming filtermail purposes + if len(params) == 1 and params[0].startswith("ORCPT"): + return {} + return super()._getparams(params) + + +class OutgoingBeforeQueueHandler: def __init__(self, config): self.config = config self.send_rate_limiter = SendRateLimiter() @@ -211,30 +232,35 @@ class BeforeQueueHandler: _, from_addr = parseaddr(message.get("from").strip()) - logging.info(f"mime-from: {from_addr} envelope-from: {envelope.mail_from!r}") if envelope.mail_from.lower() != from_addr.lower(): return f"500 Invalid FROM <{from_addr!r}> for <{envelope.mail_from!r}>" - if mail_encrypted: - print("OUTGOING: Filtering encrypted mail.", file=sys.stderr) - else: - print("OUTGOING: Filtering unencrypted mail.", file=sys.stderr) + if mail_encrypted or is_securejoin(message): + print("Outgoing: Filtering encrypted mail.", file=sys.stderr) + return + + print("Outgoing: Filtering unencrypted mail.", file=sys.stderr) if envelope.mail_from in self.config.passthrough_senders: return - if mail_encrypted or is_securejoin(message): - return + # allow self-sent Autocrypt Setup Message + if envelope.rcpt_tos == [from_addr]: + if message.get("subject") == "Autocrypt Setup Message": + if message.get_content_type() == "multipart/mixed": + return passthrough_recipients = self.config.passthrough_recipients + for recipient in envelope.rcpt_tos: if recipient_matches_passthrough(recipient, passthrough_recipients): continue - print("OUTGOING: Rejected unencrypted mail.", file=sys.stderr) - return f"500 Invalid unencrypted mail to <{recipient}>" + + print("Rejected unencrypted mail.", file=sys.stderr) + return ENCRYPTION_NEEDED_523 -class IncomingMsgsHandler: +class IncomingBeforeQueueHandler: def __init__(self, config): self.config = config @@ -244,9 +270,12 @@ class IncomingMsgsHandler: if error: return error logging.info("re-injecting the mail that passed checks") + + # the smtp daemon on reinject_port_incoming gives it to dkim milter + # which looks at source address to determine whether to verify or sign client = SMTPClient( - "127.0.0.1", - self.config.postfix_incoming_reinject_port, + "localhost", + self.config.postfix_reinject_port_incoming, source_address=("127.0.0.2", 0), ) client.sendmail( @@ -261,32 +290,27 @@ class IncomingMsgsHandler: message = BytesParser(policy=policy.default).parsebytes(envelope.content) mail_encrypted = check_encrypted(message) - if mail_encrypted: - print("INCOMING: Filtering encrypted mail.", file=sys.stderr) - else: - print("INCOMING: Filtering unencrypted mail.", file=sys.stderr) - if mail_encrypted or is_securejoin(message): + print("Incoming: Filtering encrypted mail.", file=sys.stderr) return - _, from_addr = parseaddr(message.get("from").strip()) - if from_addr.lower().startswith("mailer-daemon@"): - return + print("Incoming: Filtering unencrypted mail.", file=sys.stderr) - server_domain = self.config.mail_domain - passthrough_senders = self.config.passthrough_senders + # we want cleartext mailer-daemon messages to pass through + # chatmail core will typically not display them as normal messages + if message.get("auto-submitted"): + _, from_addr = parseaddr(message.get("from").strip()) + if from_addr.lower().startswith("mailer-daemon@"): + if message.get_content_type() == "multipart/report": + return for recipient in envelope.rcpt_tos: - if recipient_matches_passthrough(recipient, passthrough_senders): + user = self.config.get_user(recipient) + if user is None or user.is_incoming_cleartext_ok(): continue - res = recipient.split("@") - if len(res) != 2: - return f"500 Invalid address <{recipient}>" - _recipient_addr, recipient_domain = res - if server_domain == recipient_domain: - print("INCOMING: Rejected unencrypted mail.", file=sys.stderr) - return f"500 Invalid unencrypted mail to <{recipient}>" + print("Rejected unencrypted mail.", file=sys.stderr) + return ENCRYPTION_NEEDED_523 class SendRateLimiter: @@ -305,11 +329,14 @@ class SendRateLimiter: def main(): args = sys.argv[1:] - assert len(args) == 1 + assert len(args) == 2 config = read_config(args[0]) + mode = args[1] logging.basicConfig(level=logging.WARN) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - task = asyncmain_beforequeue(config) + assert mode in ["incoming", "outgoing"] + task = asyncmain_beforequeue(config, mode) loop.create_task(task) + logging.info("entering serving loop") loop.run_forever() diff --git a/chatmaild/src/chatmaild/ini/chatmail.ini.f b/chatmaild/src/chatmaild/ini/chatmail.ini.f index 1ee546e..38743d5 100644 --- a/chatmaild/src/chatmaild/ini/chatmail.ini.f +++ b/chatmaild/src/chatmaild/ini/chatmail.ini.f @@ -23,6 +23,9 @@ max_message_size = 31457280 # days after which mails are unconditionally deleted delete_mails_after = 20 +# days after which large messages (>200k) are unconditionally deleted +delete_large_after = 7 + # days after which users without a successful login are deleted (database and mails) delete_inactive_users_after = 90 @@ -46,17 +49,13 @@ passthrough_recipients = xstore@testrun.org # Deployment Details # -# where the filtermail SMTP service listens +# SMTP outgoing filtermail and reinjection filtermail_smtp_port = 10080 - -# where the filtermail SMTP service listens for incoming email -filtermail_incoming_smtp_port = 10081 - -# postfix accepts on the localhost reinject SMTP port postfix_reinject_port = 10025 -# port where postfix is listening to reinject filtered incoming email -postfix_incoming_reinject_port = 10026 +# SMTP incoming filtermail and reinjection +filtermail_smtp_port_incoming = 10081 +postfix_reinject_port_incoming = 10026 # if set to "True" IPv6 is disabled disable_ipv6 = False diff --git a/chatmaild/src/chatmaild/tests/mail-data/asm.eml b/chatmaild/src/chatmaild/tests/mail-data/asm.eml new file mode 100644 index 0000000..d7bf6ba --- /dev/null +++ b/chatmaild/src/chatmaild/tests/mail-data/asm.eml @@ -0,0 +1,56 @@ +From: {from_addr} +To: {to_addr} +Autocrypt-Setup-Message: v1 +Subject: Autocrypt Setup Message +Date: Tue, 22 Jan 2019 12:56:29 +0100 +Content-type: multipart/mixed; boundary="Y6fyGi9SoGeH8WwRaEdC6bbBcYOedDzrQ" + +--Y6fyGi9SoGeH8WwRaEdC6bbBcYOedDzrQ +Content-Type: text/plain + +This message contains all information to transfer your Autocrypt +settings along with your secret key securely from your original +device. + +To set up your new device for Autocrypt, please follow the +instuctions that should be presented by your new device. + +You can keep this message and use it as a backup for your secret +key. If you want to do this, you should write down the Setup Code +and store it securely. +--Y6fyGi9SoGeH8WwRaEdC6bbBcYOedDzrQ +Content-Type: application/autocrypt-setup +Content-Disposition: attachment; filename="autocrypt-setup-message.html" + + +

+This is the Autocrypt setup file used to transfer settings and +keys between clients. You can decrypt it using the Setup Code +presented on your old device, and then import the contained key +into your keyring. +

+ +
+-----BEGIN PGP MESSAGE-----
+Passphrase-Format: numeric9x4
+Passphrase-Begin: 17
+
+jA0EBwMCFAxADoCdzeX/0ukBlqI5+pfpKb751qd/7nLNbkpy3gVcaf1QwRPZYt40
+Ynp08UqRQ2g48ZlnzHLSwlTGOPTuv2Jt8ka+pgZ45xzvJSG2gau03xP4VsC271kR
+VmCjdb0Y6Rk96mAwfGzrkbaRQ9Z7fIoL866GOv6h9neiVIkp+JYlTV6ISD0ZQJ4Q
+I6dOQkB/TWZyVjtiJDOQHdfNWliA6NtqaLq19wlu9L5xXjuNpY95KwR8EJXWe0+o
+Y3d2U/KxOAkXKghP2Qg1GtlPVeGC5T4p03TGI6pzKT+kHX6Rrm9wK6sM9aTquMmF
+Vok84Jg1DFnwivWC2RILR81rXi7k/+Y6MUbveFgJ9cQduqpxnmD7TjOblYu7M6zp
+YGAUxh8DRKlIMn2QsA++DBYQ6ACZvwuY8qTDLkqPDo4WqM313dsMJbyGjDdVE7EM
+PESS+RlABETpZXz8g/ycr6DIUNdlbPcmYlsBfHWDOuR2GFFTwmlv5slWS39dJv38
+E0eIe1CwdxI801Se7t7dUUS/ZF8wb6GlmxOcqGbF8eko1Z0S64IAm7/h13MRQCxI
+geQnHfGYVJ2FOimoCMEKwfa9x++RFTDW0u7spDC2uWvK/1viV8OfRppFhLr/kmKb
+18lWXuAz80DAjUDUsVqEq2MvJBJGoCJUEyjuRsLkHYRM5jYk4v50LyyR0Om73nWF
+nZBqmqNzdr7Xb9PHHdFhnEc0VvoYbrcM0RVYcEMW3YbmejM891j1d6Iv+/n/qND/
+NdebGrfWJMmFLf/iEkzTZ3/v5inW9LpWoRc94ioCjJTaEo8Rib6ARRFaJVIsmNXi
+YicFGO98D+zX+a2t9Yz6IpPajVslnOp6ScpmXgts/2XWD7oE+JgxSAqo/dLVsHgP
+Ufo=
+=pulM
+-----END PGP MESSAGE-----
+
+--Y6fyGi9SoGeH8WwRaEdC6bbBcYOedDzrQ-- diff --git a/chatmaild/src/chatmaild/tests/mail-data/mailer-daemon.eml b/chatmaild/src/chatmaild/tests/mail-data/mailer-daemon.eml new file mode 100644 index 0000000..66e7c7c --- /dev/null +++ b/chatmaild/src/chatmaild/tests/mail-data/mailer-daemon.eml @@ -0,0 +1,46 @@ +Date: Fri, 8 Jul 1994 09:21:47 -0400 +From: Mail Delivery Subsystem +Subject: Returned mail: User unknown +To: +Auto-Submitted: auto-replied +MIME-Version: 1.0 +Content-Type: multipart/report; report-type=delivery-status; + boundary="JAA13167.773673707/CS.UTK.EDU" + +--JAA13167.773673707/CS.UTK.EDU +content-type: text/plain; charset=us-ascii + + ----- The following addresses had delivery problems ----- + (unrecoverable error) + (unrecoverable error) + +--JAA13167.773673707/CS.UTK.EDU +content-type: message/delivery-status + +Reporting-MTA: dns; cs.utk.edu + +Original-Recipient: rfc822;arathib@vnet.ibm.com +Final-Recipient: rfc822;arathib@vnet.ibm.com +Action: failed +Status: 5.0.0 (permanent failure) +Diagnostic-Code: smtp; + 550 'arathib@vnet.IBM.COM' is not a registered gateway user +Remote-MTA: dns; vnet.ibm.com + +Original-Recipient: rfc822;johnh@hpnjld.njd.hp.com +Final-Recipient: rfc822;johnh@hpnjld.njd.hp.com +Action: delayed +Status: 4.0.0 (hpnjld.njd.jp.com: host name lookup failure) + +Original-Recipient: rfc822;wsnell@sdcc13.ucsd.edu +Final-Recipient: rfc822;wsnell@sdcc13.ucsd.edu +Action: failed +Status: 5.0.0 +Diagnostic-Code: smtp; 550 user unknown +Remote-MTA: dns; sdcc13.ucsd.edu + +--JAA13167.773673707/CS.UTK.EDU +content-type: message/rfc822 + +[original message goes here] +--JAA13167.773673707/CS.UTK.EDU-- diff --git a/chatmaild/src/chatmaild/tests/test_config.py b/chatmaild/src/chatmaild/tests/test_config.py index 63d237c..6ef3c61 100644 --- a/chatmaild/src/chatmaild/tests/test_config.py +++ b/chatmaild/src/chatmaild/tests/test_config.py @@ -15,6 +15,14 @@ def test_read_config_basic(example_config): assert example_config.mail_domain == "chat.example.org" +def test_read_config_basic_using_defaults(tmp_path, maildomain): + inipath = tmp_path.joinpath("chatmail.ini") + inipath.write_text(f"[params]\nmail_domain = {maildomain}") + example_config = read_config(inipath) + assert example_config.max_user_send_per_minute == 60 + assert example_config.filtermail_smtp_port_incoming == 10081 + + def test_read_config_testrun(make_config): config = make_config("something.testrun.org") assert config.mail_domain == "something.testrun.org" @@ -27,6 +35,7 @@ def test_read_config_testrun(make_config): assert config.max_user_send_per_minute == 60 assert config.max_mailbox_size == "100M" assert config.delete_mails_after == "20" + assert config.delete_large_after == "7" assert config.username_min_length == 9 assert config.username_max_length == 9 assert config.password_min_length == 9 diff --git a/chatmaild/src/chatmaild/tests/test_filtermail.py b/chatmaild/src/chatmaild/tests/test_filtermail.py index efbfc17..284dbef 100644 --- a/chatmaild/src/chatmaild/tests/test_filtermail.py +++ b/chatmaild/src/chatmaild/tests/test_filtermail.py @@ -1,7 +1,8 @@ import pytest from chatmaild.filtermail import ( - BeforeQueueHandler, + IncomingBeforeQueueHandler, + OutgoingBeforeQueueHandler, SendRateLimiter, check_armored_payload, check_encrypted, @@ -18,7 +19,13 @@ def maildomain(): @pytest.fixture def handler(make_config, maildomain): config = make_config(maildomain) - return BeforeQueueHandler(config) + return OutgoingBeforeQueueHandler(config) + + +@pytest.fixture +def inhandler(make_config, maildomain): + config = make_config(maildomain) + return IncomingBeforeQueueHandler(config) def test_reject_forged_from(maildata, gencreds, handler): @@ -127,13 +134,27 @@ def test_cleartext_excempt_privacy(maildata, gencreds, handler): rcpt_tos = [to_addr, false_to] content = msg.as_bytes() - assert "500" in handler.check_DATA(envelope=env2) + assert "523" in handler.check_DATA(envelope=env2) -def test_cleartext_self_send_fails(maildata, gencreds, handler): +def test_cleartext_self_send_autocrypt_setup_message(maildata, gencreds, handler): from_addr = gencreds()[0] to_addr = from_addr + msg = maildata("asm.eml", from_addr=from_addr, to_addr=to_addr) + + class env: + mail_from = from_addr + rcpt_tos = [to_addr] + content = msg.as_bytes() + + assert not handler.check_DATA(envelope=env) + + +def test_cleartext_send_fails(maildata, gencreds, handler): + from_addr = gencreds()[0] + to_addr = gencreds()[0] + msg = maildata("plain.eml", from_addr=from_addr, to_addr=to_addr) class env: @@ -142,7 +163,41 @@ def test_cleartext_self_send_fails(maildata, gencreds, handler): content = msg.as_bytes() res = handler.check_DATA(envelope=env) - assert "500 Invalid unencrypted" in res + assert "523 Encryption Needed" in res + + +def test_cleartext_incoming_fails(maildata, gencreds, inhandler): + from_addr = gencreds()[0] + to_addr, password = gencreds() + + msg = maildata("plain.eml", from_addr=from_addr, to_addr=to_addr) + + class env: + mail_from = from_addr + rcpt_tos = [to_addr] + content = msg.as_bytes() + + user = inhandler.config.get_user(to_addr) + user.set_password(password) + res = inhandler.check_DATA(envelope=env) + assert "523 Encryption Needed" in res + + user.allow_incoming_cleartext() + assert not inhandler.check_DATA(envelope=env) + + +def test_cleartext_incoming_mailer_daemon(maildata, gencreds, inhandler): + from_addr = "mailer-daemon@example.org" + to_addr = gencreds()[0] + + msg = maildata("mailer-daemon.eml", from_addr=from_addr, to_addr=to_addr) + + class env: + mail_from = from_addr + rcpt_tos = [to_addr] + content = msg.as_bytes() + + assert not inhandler.check_DATA(envelope=env) def test_cleartext_passthrough_domains(maildata, gencreds, handler): @@ -166,7 +221,7 @@ def test_cleartext_passthrough_domains(maildata, gencreds, handler): rcpt_tos = [to_addr, false_to] content = msg.as_bytes() - assert "500" in handler.check_DATA(envelope=env2) + assert "523" in handler.check_DATA(envelope=env2) def test_cleartext_passthrough_senders(gencreds, handler, maildata): diff --git a/chatmaild/src/chatmaild/tests/test_user.py b/chatmaild/src/chatmaild/tests/test_user.py index e6f944f..3e7b506 100644 --- a/chatmaild/src/chatmaild/tests/test_user.py +++ b/chatmaild/src/chatmaild/tests/test_user.py @@ -40,3 +40,17 @@ def test_no_mailboxes_dir(testaddr, example_config, tmp_path): user.set_password("someeqkjwelkqwjleqwe") user.set_last_login_timestamp(100000) assert user.get_last_login_timestamp() == 86400 + + +def test_set_get_cleartext_flag(testaddr, example_config, tmp_path): + p = tmp_path.joinpath("a", "mailboxes") + example_config.mailboxes_dir = p + + user = example_config.get_user(testaddr) + user.set_password("someeqkjwelkqwjleqwe") + user.set_last_login_timestamp(100000) + assert user.get_last_login_timestamp() == 86400 + + assert not user.is_incoming_cleartext_ok() + user.allow_incoming_cleartext() + assert user.is_incoming_cleartext_ok() diff --git a/chatmaild/src/chatmaild/user.py b/chatmaild/src/chatmaild/user.py index e9030e4..3ef4fc8 100644 --- a/chatmaild/src/chatmaild/user.py +++ b/chatmaild/src/chatmaild/user.py @@ -13,6 +13,7 @@ class User: self.maildir = maildir self.addr = addr self.password_path = password_path + self.enforce_E2EE_path = maildir.joinpath("enforceE2EEincoming") self.uid = uid self.gid = gid @@ -35,6 +36,13 @@ class User: home = str(self.maildir) return dict(addr=self.addr, home=home, uid=self.uid, gid=self.gid, password=pw) + def is_incoming_cleartext_ok(self): + return not self.enforce_E2EE_path.exists() + + def allow_incoming_cleartext(self): + if self.enforce_E2EE_path.exists(): + self.enforce_E2EE_path.unlink() + def set_password(self, enc_password): """Set the specified password for this user. @@ -50,6 +58,7 @@ class User: if not self.addr.startswith("echo@"): logging.error(f"could not write password for: {self.addr}") raise + self.enforce_E2EE_path.touch() def set_last_login_timestamp(self, timestamp): """Track login time with daily granularity diff --git a/cmdeploy/src/cmdeploy/__init__.py b/cmdeploy/src/cmdeploy/__init__.py index 238ad25..ee26b7b 100644 --- a/cmdeploy/src/cmdeploy/__init__.py +++ b/cmdeploy/src/cmdeploy/__init__.py @@ -11,6 +11,7 @@ from pathlib import Path from chatmaild.config import Config, read_config from pyinfra import facts, host +from pyinfra.api import FactBase from pyinfra.facts.files import File from pyinfra.facts.systemd import SystemdEnabled from pyinfra.operations import apt, files, pip, server, systemd @@ -18,6 +19,21 @@ from pyinfra.operations import apt, files, pip, server, systemd from .acmetool import deploy_acmetool +class Port(FactBase): + """ + Returns the process occuping a port. + """ + + def command(self, port: int) -> str: + return ( + "ss -lptn 'src :%d' | awk 'NR>1 {print $6,$7}' | sed 's/users:((\"//;s/\".*//'" + % (port,) + ) + + def process(self, output: [str]) -> str: + return output[0] + + def _build_chatmaild(dist_dir) -> None: dist_dir = Path(dist_dir).resolve() if dist_dir.exists(): @@ -106,12 +122,14 @@ def _install_remote_venv_with_chatmaild(config) -> None: for fn in ( "doveauth", "filtermail", + "filtermail-incoming", # "echobot", "chatmail-metadata", "lastlogin", ): + execpath = fn if fn != "filtermail-incoming" else "filtermail" params = dict( - execpath=f"{remote_venv_dir}/bin/{fn}", + execpath=f"{remote_venv_dir}/bin/{execpath}", config_path=remote_chatmail_inipath, remote_venv_dir=remote_venv_dir, mail_domain=config.mail_domain, @@ -228,7 +246,6 @@ def _configure_opendkim(domain: str, dkim_selector: str = "dkim") -> bool: ) need_restart |= service_file.changed - return need_restart @@ -556,7 +573,6 @@ def deploy_chatmail(config_path: Path, disable_mail: bool) -> None: server.group(name="Create vmail group", group="vmail", system=True) server.user(name="Create vmail user", user="vmail", group="vmail", system=True) - server.user(name="Create filtermail user", user="filtermail", system=True) server.group(name="Create opendkim group", group="opendkim", system=True) server.user( name="Create opendkim user", @@ -591,6 +607,12 @@ def deploy_chatmail(config_path: Path, disable_mail: bool) -> None: ensure_newline=True, ) + if host.get_fact(Port, port=53) != "unbound": + files.line( + name="Add 9.9.9.9 to resolv.conf", + path="/etc/resolv.conf", + line="nameserver 9.9.9.9", + ) apt.update(name="apt update", cache_time=24 * 3600) apt.upgrade(name="upgrade apt packages", auto_remove=True) @@ -602,6 +624,12 @@ def deploy_chatmail(config_path: Path, disable_mail: bool) -> None: # Run local DNS resolver `unbound`. # `resolvconf` takes care of setting up /etc/resolv.conf # to use 127.0.0.1 as the resolver. + from cmdeploy.cmdeploy import Out + + process_on_53 = host.get_fact(Port, port=53) + if process_on_53 not in (None, "unbound"): + Out().red(f"Can't install unbound: port 53 is occupied by: {process_on_53}") + exit(1) apt.packages( name="Install unbound", packages=["unbound", "unbound-anchor", "dnsutils"], diff --git a/cmdeploy/src/cmdeploy/cmdeploy.py b/cmdeploy/src/cmdeploy/cmdeploy.py index 609e331..be33ffe 100644 --- a/cmdeploy/src/cmdeploy/cmdeploy.py +++ b/cmdeploy/src/cmdeploy/cmdeploy.py @@ -86,15 +86,19 @@ def run_cmd(args, out): out.red("Please re-run scripts/initenv.sh to update pyinfra to version 3.") return 1 - retcode = out.check_call(cmd, env=env) - if retcode == 0: - out.green("Deploy completed, call `cmdeploy dns` next.") - elif not remote_data["acme_account_url"]: - out.red("Deploy completed but letsencrypt not configured") - out.red("Run 'cmdeploy run' again") - retcode = 0 - else: + try: + retcode = out.check_call(cmd, env=env) + if retcode == 0: + out.green("Deploy completed, call `cmdeploy dns` next.") + elif not remote_data["acme_account_url"]: + out.red("Deploy completed but letsencrypt not configured") + out.red("Run 'cmdeploy run' again") + retcode = 0 + else: + out.red("Deploy failed") + except subprocess.CalledProcessError: out.red("Deploy failed") + retcode = 1 return retcode diff --git a/cmdeploy/src/cmdeploy/dovecot/expunge.cron.j2 b/cmdeploy/src/cmdeploy/dovecot/expunge.cron.j2 index 73ab321..9eb2718 100644 --- a/cmdeploy/src/cmdeploy/dovecot/expunge.cron.j2 +++ b/cmdeploy/src/cmdeploy/dovecot/expunge.cron.j2 @@ -1,5 +1,5 @@ # delete already seen big mails after 7 days, in the INBOX -2 0 * * * vmail find {{ config.mailboxes_dir }} -path '*/cur/*' -mtime +7 -size +200k -type f -delete +2 0 * * * vmail find {{ config.mailboxes_dir }} -path '*/cur/*' -mtime +{{ config.delete_large_after }} -size +200k -type f -delete # delete all mails after {{ config.delete_mails_after }} days, in the Inbox 2 0 * * * vmail find {{ config.mailboxes_dir }} -path '*/cur/*' -mtime +{{ config.delete_mails_after }} -type f -delete # or in any IMAP subfolder diff --git a/cmdeploy/src/cmdeploy/postfix/master.cf.j2 b/cmdeploy/src/cmdeploy/postfix/master.cf.j2 index c452104..49c745d 100644 --- a/cmdeploy/src/cmdeploy/postfix/master.cf.j2 +++ b/cmdeploy/src/cmdeploy/postfix/master.cf.j2 @@ -14,7 +14,7 @@ smtp inet n - y - - smtpd -v {%- else %} smtp inet n - y - - smtpd {%- endif %} - -o smtpd_proxy_filter=127.0.0.1:{{ config.filtermail_incoming_smtp_port }} + -o smtpd_proxy_filter=127.0.0.1:{{ config.filtermail_smtp_port_incoming }} submission inet n - y - 5000 smtpd -o syslog_name=postfix/submission -o smtpd_tls_security_level=encrypt @@ -76,14 +76,15 @@ anvil unix - - y - 1 anvil scache unix - - y - 1 scache postlog unix-dgram n - n - 1 postlogd filter unix - n n - - lmtp -# Local SMTP server for reinjecting filered mail. -localhost:{{ config.postfix_reinject_port }} inet n - n - 10 smtpd +# Local SMTP server for reinjecting outgoing filtered mail. +127.0.0.1:{{ config.postfix_reinject_port }} inet n - n - 10 smtpd -o syslog_name=postfix/reinject -o smtpd_milters=unix:opendkim/opendkim.sock -o cleanup_service_name=authclean -# Local SMTP server for reinjecting filered incoming mail. -localhost:{{ config.postfix_incoming_reinject_port }} inet n - n - 10 smtpd - -o syslog_name=postfix/reinject + +# Local SMTP server for reinjecting incoming filtered mail +127.0.0.1:{{ config.postfix_reinject_port_incoming }} inet n - n - 10 smtpd + -o syslog_name=postfix/reinject_incoming -o smtpd_milters=unix:opendkim/opendkim.sock # Cleanup `Received` headers for authenticated mail diff --git a/cmdeploy/src/cmdeploy/remote/rdns.py b/cmdeploy/src/cmdeploy/remote/rdns.py index 317fa51..fd847ef 100644 --- a/cmdeploy/src/cmdeploy/remote/rdns.py +++ b/cmdeploy/src/cmdeploy/remote/rdns.py @@ -19,7 +19,7 @@ def perform_initial_checks(mail_domain): """Collecting initial DNS settings.""" assert mail_domain if not shell("dig", fail_ok=True): - shell("apt-get install -y dnsutils") + shell("apt-get update && apt-get install -y dnsutils") A = query_dns("A", mail_domain) AAAA = query_dns("AAAA", mail_domain) MTA_STS = query_dns("CNAME", f"mta-sts.{mail_domain}") diff --git a/cmdeploy/src/cmdeploy/remote/rshell.py b/cmdeploy/src/cmdeploy/remote/rshell.py index a07f539..042c5bf 100644 --- a/cmdeploy/src/cmdeploy/remote/rshell.py +++ b/cmdeploy/src/cmdeploy/remote/rshell.py @@ -1,10 +1,13 @@ -from subprocess import CalledProcessError, check_output +from subprocess import DEVNULL, CalledProcessError, check_output def shell(command, fail_ok=False): print(f"$ {command}") + args = dict(shell=True) + if fail_ok: + args["stderr"] = DEVNULL try: - return check_output(command, shell=True).decode().rstrip() + return check_output(command, **args).decode().rstrip() except CalledProcessError: if not fail_ok: raise diff --git a/cmdeploy/src/cmdeploy/service/filtermail-incoming.service.f b/cmdeploy/src/cmdeploy/service/filtermail-incoming.service.f new file mode 100644 index 0000000..844843e --- /dev/null +++ b/cmdeploy/src/cmdeploy/service/filtermail-incoming.service.f @@ -0,0 +1,12 @@ +[Unit] +Description=Incoming Chatmail Postfix before queue filter + +[Service] +ExecStart={execpath} {config_path} incoming +Restart=always +RestartSec=30 +User=vmail + +[Install] +WantedBy=multi-user.target + diff --git a/cmdeploy/src/cmdeploy/service/filtermail.service.f b/cmdeploy/src/cmdeploy/service/filtermail.service.f index d0f9d3f..398d5a8 100644 --- a/cmdeploy/src/cmdeploy/service/filtermail.service.f +++ b/cmdeploy/src/cmdeploy/service/filtermail.service.f @@ -1,11 +1,11 @@ [Unit] -Description=Chatmail Postfix before queue filter +Description=Outgoing Chatmail Postfix before queue filter [Service] -ExecStart={execpath} {config_path} +ExecStart={execpath} {config_path} outgoing Restart=always RestartSec=30 -User=filtermail +User=vmail [Install] WantedBy=multi-user.target diff --git a/cmdeploy/src/cmdeploy/tests/online/benchmark.py b/cmdeploy/src/cmdeploy/tests/online/benchmark.py index 01de017..ab01501 100644 --- a/cmdeploy/src/cmdeploy/tests/online/benchmark.py +++ b/cmdeploy/src/cmdeploy/tests/online/benchmark.py @@ -37,7 +37,7 @@ class TestDC: def test_ping_pong(self, benchmark, cmfactory): ac1, ac2 = cmfactory.get_online_accounts(2) - chat = cmfactory.get_accepted_chat(ac1, ac2) + chat = cmfactory.get_protected_chat(ac1, ac2) def dc_ping_pong(): chat.send_text("ping") @@ -49,7 +49,7 @@ class TestDC: def test_send_10_receive_10(self, benchmark, cmfactory, lp): ac1, ac2 = cmfactory.get_online_accounts(2) - chat = cmfactory.get_accepted_chat(ac1, ac2) + chat = cmfactory.get_protected_chat(ac1, ac2) def dc_send_10_receive_10(): for i in range(10): diff --git a/cmdeploy/src/cmdeploy/tests/online/test_0_login.py b/cmdeploy/src/cmdeploy/tests/online/test_0_login.py index 5f4f977..69f79f7 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_0_login.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_0_login.py @@ -90,8 +90,13 @@ def test_concurrent_logins_same_account( def test_no_vrfy(chatmail_config): + domain = chatmail_config.mail_domain sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((chatmail_config.mail_domain, 25)) + sock.settimeout(10) + try: + sock.connect((domain, 25)) + except socket.timeout: + pytest.skip(f"port 25 not reachable for {domain}") banner = sock.recv(1024) print(banner) sock.send(b"VRFY wrongaddress@%s\r\n" % (chatmail_config.mail_domain.encode(),)) diff --git a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py index 980d706..6ab9690 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py @@ -55,11 +55,12 @@ class TestSSHExecutor: def test_opendkim_restarted(self, sshexec): """check that opendkim is not running for longer than a day.""" - out = sshexec(call=remote.rshell.shell, kwargs=dict(command="systemctl status opendkim")) - assert type(out) == str - since_date_str = out.split("since ")[1].split(";")[0] - since_date = datetime.datetime.strptime(since_date_str, "%a %Y-%m-%d %H:%M:%S %Z") - assert (datetime.datetime.now() - since_date).total_seconds() < 60 * 60 * 24 + cmd = "systemctl show opendkim --timestamp=utc --property=ActiveEnterTimestamp" + out = sshexec(call=remote.rshell.shell, kwargs=dict(command=cmd)) + datestring = out.split("=")[1] + since_date = datetime.datetime.strptime(datestring, "%a %Y-%m-%d %H:%M:%S %Z") + now = datetime.datetime.now(since_date.tzinfo) + assert (now - since_date).total_seconds() < 60 * 60 * 51 def test_remote(remote, imap_or_smtp): @@ -118,7 +119,12 @@ def test_authenticated_from(cmsetup, maildata): def test_reject_missing_dkim(cmsetup, maildata, from_addr): recipient = cmsetup.gen_users(1)[0] msg = maildata("encrypted.eml", from_addr=from_addr, to_addr=recipient.addr).as_string() - with smtplib.SMTP(cmsetup.maildomain, 25) as s: + try: + conn = smtplib.SMTP(cmsetup.maildomain, 25, timeout=10) + except TimeoutError: + pytest.skip(f"port 25 not reachable for {cmsetup.maildomain}") + + with conn as s: with pytest.raises(smtplib.SMTPDataError, match="No valid DKIM signature"): s.sendmail(from_addr=from_addr, to_addrs=recipient.addr, msg=msg) @@ -176,6 +182,8 @@ def test_expunged(remote, chatmail_config): f"find {chatmail_config.mailboxes_dir} -path '*/tmp/*' -mtime +{outdated_days} -type f", f"find {chatmail_config.mailboxes_dir} -path '*/.*/tmp/*' -mtime +{outdated_days} -type f", ] + outdated_days = int(chatmail_config.delete_large_after) + 1 + find_cmds.append("find {chatmail_config.mailboxes_dir} -path '*/cur/*' -mtime +{outdated_days} -size +200k -type f") for cmd in find_cmds: for line in remote.iter_output(cmd): assert not line diff --git a/cmdeploy/src/cmdeploy/tests/online/test_2_deltachat.py b/cmdeploy/src/cmdeploy/tests/online/test_2_deltachat.py index cb31a47..b50dc5b 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_2_deltachat.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_2_deltachat.py @@ -173,7 +173,7 @@ def test_echobot(cmfactory, chatmail_config, lp, sshdomain): ac._evtracker.wait_securejoin_joiner_progress(1000) # send message and check it gets replied back - lp.sec(f"Send message to echobot") + lp.sec("Send message to echobot") text = "hi, I hope you text me back" chat.send_text(text) lp.sec("Wait for reply from echobot") diff --git a/cmdeploy/src/cmdeploy/tests/plugin.py b/cmdeploy/src/cmdeploy/tests/plugin.py index b4f17fa..4ffd7a1 100644 --- a/cmdeploy/src/cmdeploy/tests/plugin.py +++ b/cmdeploy/src/cmdeploy/tests/plugin.py @@ -62,7 +62,7 @@ def sshdomain(maildomain): def maildomain2(): domain = os.environ.get("CHATMAIL_DOMAIN2") if not domain: - pytest.skip("set CHATMAIL_DOMAIN2 to a ssh-reachable chatmail instance") + pytest.skip("set CHATMAIL_DOMAIN2 to a second chatmail server") return domain diff --git a/www/src/info.md b/www/src/info.md index 3556249..1fd7eb5 100644 --- a/www/src/info.md +++ b/www/src/info.md @@ -6,29 +6,6 @@ interoperable e-mail service for everyone. What's behind a `chatmail` is effectively a normal e-mail address just like any other but optimized for the usage in chats, especially DeltaChat. -### Choosing a chatmail address instead of using a random one - -In the Delta Chat account setup you may tap `Create a profile` then `Use other server` and choose `Classic e-mail login`. Here fill the two fields like this: - -- `E-Mail Address`: invent a word with -{% if username_min_length == username_max_length %} - *exactly* {{ username_min_length }} -{% else %} - {{ username_min_length}} - {% if username_max_length == "more" %} - or more - {% else %} - to {{ username_max_length }} - {% endif %} -{% endif %} - characters - and append `@{{config.mail_domain}}` to it. - -- `Existing Password`: invent at least {{ password_min_length }} characters. - -If the e-mail address is not yet taken, you'll get that account. -The first login sets your password. - ### Rate and storage limits @@ -38,10 +15,11 @@ The first login sets your password. - You may send up to {{ config.max_user_send_per_minute }} messages per minute. -- Messages are unconditionally removed {{ config.delete_mails_after }} days after arriving on the server. - - You can store up to [{{ config.max_mailbox_size }} messages on the server](https://delta.chat/en/help#what-happens-if-i-turn-on-delete-old-messages-from-server). +- Messages are unconditionally removed latest {{ config.delete_mails_after }} days after arriving on the server. + Earlier, if storage may exceed otherwise. + ### Account deletion