From c4f0146e16376a70c36abb18a70481b78f9b4bb1 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Tue, 1 Apr 2025 20:52:43 +0200 Subject: [PATCH 01/27] Reject unencrypted incoming mail (#538) * draft blocking of incoming non-encrypted mail * create a new enforceE2EE file in address dirs by default and only accept incoming cleartext file if the enforceE2EE file is missing * Update cmdeploy/src/cmdeploy/service/filtermail.service.f Co-authored-by: l * fix benchmark so they setup encryption * hack around limitations of aiosmtpd's handliung of RCPTO options * add tests, and split incoming/outgoing handlers for clarity * document mailbox directory structure, some streamlining of features/E2EE in intro * use SMTP response code "523 Encryption Needed" * filtermail: care for the case that the recipient does not exist Co-authored-by: missytake * Update chatmaild/src/chatmaild/filtermail.py Co-authored-by: l * Update chatmaild/src/chatmaild/filtermail.py Co-authored-by: l * remove debug info print * ensure multipart/report type for mailer-daemon messages * Allow sending out Autocrypt Setup Messages --------- Co-authored-by: l Co-authored-by: missytake --- CHANGELOG.md | 9 ++ README.md | 35 ++++-- chatmaild/src/chatmaild/config.py | 6 + chatmaild/src/chatmaild/filtermail.py | 110 +++++++++++++++--- chatmaild/src/chatmaild/ini/chatmail.ini.f | 8 +- .../src/chatmaild/tests/mail-data/asm.eml | 56 +++++++++ .../tests/mail-data/mailer-daemon.eml | 46 ++++++++ .../src/chatmaild/tests/test_filtermail.py | 67 ++++++++++- chatmaild/src/chatmaild/tests/test_user.py | 14 +++ chatmaild/src/chatmaild/user.py | 9 ++ cmdeploy/src/cmdeploy/__init__.py | 5 +- cmdeploy/src/cmdeploy/postfix/master.cf.j2 | 9 +- .../service/filtermail-incoming.service.f | 12 ++ .../src/cmdeploy/service/filtermail.service.f | 6 +- .../src/cmdeploy/tests/online/benchmark.py | 4 +- .../cmdeploy/tests/online/test_2_deltachat.py | 2 +- cmdeploy/src/cmdeploy/tests/plugin.py | 2 +- 17 files changed, 358 insertions(+), 42 deletions(-) create mode 100644 chatmaild/src/chatmaild/tests/mail-data/asm.eml create mode 100644 chatmaild/src/chatmaild/tests/mail-data/mailer-daemon.eml create mode 100644 cmdeploy/src/cmdeploy/service/filtermail-incoming.service.f diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c68ed2..aa18c8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## untagged +- 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)) diff --git a/README.md b/README.md index 6da9447..e13b79b 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,23 @@ -# Chatmail servers for secure instant messaging +# Chatmail servers for end-to-end encrypted instant messaging -Chatmail servers are interoperable email routing machines optimized for: +Chatmail servers are interoperable e-mail routing machines optimized 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 well under a second. -- **Security:** Strict TLS, DKIM and OpenPGP with metadata-minimization rules enforced. +- **Transport Security:** Strict TLS and DKIM enforced. -- **Reliability:** No spam or IP reputation checks, rate-limits suitable for realtime chats. +- **Reliability:** No spam or IP reputation checks; rate-limits are suitable for realtime chats. - **Efficiency:** Messages are only stored for transit and removed automatically. @@ -191,9 +194,9 @@ A short overview: 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. +- [`filtermail`](https://github.com/chatmail/server/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/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) @@ -237,7 +240,6 @@ by the according markdown `.md` file in the `www/src` directory. ### Refining the web pages - ``` scripts/cmdeploy webdev ``` @@ -252,6 +254,23 @@ This starts a local live development cycle for chatmail web pages: - Starts a browser window automatically where you can "refresh" as needed. +## Mailbox directory layout + +Fresh chatmail server 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 account creation diff --git a/chatmaild/src/chatmaild/config.py b/chatmaild/src/chatmaild/config.py index 670b204..e5e797a 100644 --- a/chatmaild/src/chatmaild/config.py +++ b/chatmaild/src/chatmaild/config.py @@ -29,7 +29,13 @@ 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_smtp_port_incoming = int( + params["filtermail_smtp_port_incoming"] + ) self.postfix_reinject_port = int(params["postfix_reinject_port"]) + 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" self.imap_rawlog = params.get("imap_rawlog", "false").lower() == "true" diff --git a/chatmaild/src/chatmaild/filtermail.py b/chatmaild/src/chatmaild/filtermail.py index 25d9248..f66188e 100644 --- a/chatmaild/src/chatmaild/filtermail.py +++ b/chatmaild/src/chatmaild/filtermail.py @@ -11,9 +11,12 @@ from email.utils import parseaddr from smtplib import SMTP as SMTPClient 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. @@ -157,9 +160,14 @@ def check_encrypted(message): return True -async def asyncmain_beforequeue(config): - port = config.filtermail_smtp_port - Controller(BeforeQueueHandler(config), hostname="127.0.0.1", port=port).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): @@ -171,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() @@ -210,28 +232,85 @@ 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("Filtering encrypted mail.", file=sys.stderr) - else: - print("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("Rejected unencrypted mail.", file=sys.stderr) - return "500 Invalid unencrypted mail" + return ENCRYPTION_NEEDED_523 + + +class IncomingBeforeQueueHandler: + def __init__(self, config): + self.config = config + + async def handle_DATA(self, server, session, envelope): + logging.info("handle_DATA before-queue") + error = self.check_DATA(envelope) + 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( + "localhost", + self.config.postfix_reinject_port_incoming, + source_address=("127.0.0.2", 0), + ) + client.sendmail( + envelope.mail_from, envelope.rcpt_tos, envelope.original_content + ) + return "250 OK" + + def check_DATA(self, envelope): + """the central filtering function for e-mails.""" + logging.info(f"Processing DATA message from {envelope.mail_from}") + + message = BytesParser(policy=policy.default).parsebytes(envelope.content) + mail_encrypted = check_encrypted(message) + + if mail_encrypted or is_securejoin(message): + print("Incoming: Filtering encrypted mail.", file=sys.stderr) + return + + print("Incoming: Filtering unencrypted mail.", file=sys.stderr) + + # 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: + user = self.config.get_user(recipient) + if user is None or user.is_incoming_cleartext_ok(): + continue + + print("Rejected unencrypted mail.", file=sys.stderr) + return ENCRYPTION_NEEDED_523 class SendRateLimiter: @@ -250,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 60fe1dc..d9e5261 100644 --- a/chatmaild/src/chatmaild/ini/chatmail.ini.f +++ b/chatmaild/src/chatmaild/ini/chatmail.ini.f @@ -46,12 +46,14 @@ passthrough_recipients = xstore@testrun.org # Deployment Details # -# where the filtermail SMTP service listens +# SMTP outgoing filtermail and reinjection filtermail_smtp_port = 10080 - -# postfix accepts on the localhost reinject SMTP port postfix_reinject_port = 10025 +# 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_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 a80db7c..e12c53c 100644 --- a/cmdeploy/src/cmdeploy/__init__.py +++ b/cmdeploy/src/cmdeploy/__init__.py @@ -106,12 +106,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, @@ -541,7 +543,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", diff --git a/cmdeploy/src/cmdeploy/postfix/master.cf.j2 b/cmdeploy/src/cmdeploy/postfix/master.cf.j2 index 494cd0c..3573da7 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_milters=unix:opendkim/opendkim.sock + -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,12 +76,17 @@ 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. +# Local SMTP server for reinjecting outgoing filtered mail. localhost:{{ 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 incoming filtered mail +localhost:{{ 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 # to avoid leaking client IP. # 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_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 From fc3fb934322600240852400ae84c7a561a75db8e Mon Sep 17 00:00:00 2001 From: holger krekel Date: Tue, 1 Apr 2025 21:42:44 +0200 Subject: [PATCH 02/27] use default config files for any missing ini setting --- chatmaild/src/chatmaild/config.py | 14 +++++++++++--- chatmaild/src/chatmaild/tests/test_config.py | 8 ++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/chatmaild/src/chatmaild/config.py b/chatmaild/src/chatmaild/config.py index e5e797a..8edb192 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: @@ -75,6 +79,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 +128,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/tests/test_config.py b/chatmaild/src/chatmaild/tests/test_config.py index 63d237c..542084a 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" From 6d898d54313f273d4f85e5ded945718cbd52bb74 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Wed, 2 Apr 2025 16:23:23 +0200 Subject: [PATCH 03/27] use "relay" instead of "server" in most places, and "address" instead of "account" (#539) * use "relay" instead of "server" and "address" instead of "account" * consistent Dovecot capitalization and striking relay in two places * address missytake's comments: use "chatmail relay servers" sometimes -- it's still fine to talk about relays being, or running on, servers --- README.md | 189 +++++++++++++++++++++++++++--------------------------- 1 file changed, 96 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index e13b79b..957a1ec 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,29 @@ -# Chatmail servers for end-to-end encrypted instant messaging +# Chatmail relays for end-to-end encrypted instant e-mail -Chatmail servers are interoperable e-mail routing machines optimized for +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 +- **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 +- **Instant:** Privacy-preserving Push Notifications for Apple, Google, and Huawei -- **Speed:** Message delivery in well under a second. +- **Speed:** Message delivery in half a second, with optional P2P realtime connections -- **Transport Security:** Strict TLS and DKIM enforced. +- **Transport Security:** Strict TLS and DKIM enforced -- **Reliability:** No spam or IP reputation checks; rate-limits are suitable for realtime chats. +- **Reliability:** No spam or IP reputation checks; rate-limits are suitable for realtime chats -- **Efficiency:** Messages are only stored for transit and removed automatically. +- **Efficiency:** Messages are only stored for transit and removed automatically -This repository contains everything needed to setup a ready-to-use chatmail server +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) services. +[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. @@ -31,8 +31,8 @@ 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). +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 @@ -43,11 +43,11 @@ You will need the following: - 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 + 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 server's root user. - You must add a passphrase-protected private key to the local ssh-agent +- 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)) @@ -72,8 +72,8 @@ Please substitute it with your own domain. 2. Clone the repository and bootstrap the Python virtualenv. ``` - git clone https://github.com/chatmail/server - cd server + git clone https://github.com/chatmail/relay + cd relay scripts/initenv.sh ``` @@ -90,7 +90,7 @@ Please substitute it with your own domain. ``` -5. Deploy to the remote chatmail server: +5. Deploy the remote chatmail relay server: ``` scripts/cmdeploy run @@ -130,11 +130,11 @@ scripts/cmdeploy bench This repository has four directories: -- [cmdeploy](https://github.com/chatmail/server/tree/main/cmdeploy) +- [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/server/tree/main/chatmaild) +- [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, @@ -143,12 +143,12 @@ This repository has four directories: 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) +- [www](https://github.com/chatmail/relay/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. + 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/server/tree/main/scripts) +- [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 @@ -160,14 +160,15 @@ 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, +to automatically install or upgrade all chatmail components on a relay, 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) +- [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 server](https://www.dovecot.org) stores messages for your users until they download them +- [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 @@ -177,49 +178,50 @@ The components of chatmail are: - [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 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: +`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/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 +- [`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 users - to send mails for them. + to authenticate logins. -- [`filtermail`](https://github.com/chatmail/server/blob/main/chatmaild/src/chatmaild/filtermail.py) +- [`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/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. +- [`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/server/blob/main/chatmaild/src/chatmaild/notifier.py) + 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/server/blob/main/chatmaild/src/chatmaild/delete_inactive_users.py) +- [`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/server/blob/main/chatmaild/src/chatmaild/lastlogin.py) - is contacted by dovecot when a user logs in +- [`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/server/blob/main/chatmaild/src/chatmaild/echo.py) +- [`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/server/blob/main/chatmaild/src/chatmaild/metrics.py) +- [`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 @@ -228,7 +230,7 @@ A short overview: 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 + create an address on your chatmail relay - a default `info.html` that is linked from the home page @@ -256,7 +258,7 @@ This starts a local live development cycle for chatmail web pages: ## Mailbox directory layout -Fresh chatmail server addresses have a mailbox directory that contains: +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. @@ -272,17 +274,17 @@ Fresh chatmail server addresses have a mailbox directory that contains: for a while. -## Emergency Commands to disable automatic account creation +## Emergency Commands to disable automatic address 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: +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 ``` -Account creation will be denied while this file is present. +Chatmail address creation will be denied while this file is present. ### Ports @@ -293,11 +295,11 @@ Port 443 multiplexes HTTPS, IMAP and SMTP using ALPN to redirect connections to [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. +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 servers rely on [DKIM](https://www.rfc-editor.org/rfc/rfc6376) +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) @@ -324,20 +326,20 @@ this is ensured by `filtermail` proxy. 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. +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 server domain -and then connecting to MX servers (e.g `mx.example.org`) with +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 server, +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 Exim server and don't see incoming connections -from a chatmail server in the logs, +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 @@ -346,9 +348,9 @@ 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 +## Migrating a chatmail relay to a new host -If you want to migrate chatmail from an old machine +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; @@ -356,8 +358,8 @@ 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`. +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. @@ -365,7 +367,7 @@ 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. +1. First, disable mail services on the old site. ``` cmdeploy run --disable-mail --ssh-host 13.37.13.37 @@ -375,16 +377,15 @@ in this case, just run `ssh-keygen -R "mail.example.org"` as recommended. 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: - +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 accounts, the TLS certificate, DKIM keys (so DKIM DNS record remains valid), and the echobot's password so it continues to function. + 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: @@ -392,9 +393,10 @@ in this case, just run `ssh-keygen -R "mail.example.org"` as recommended. ``` 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. + 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 server, run the following to ensure the ownership is correct in case UIDs/GIDs changed: +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 @@ -403,46 +405,47 @@ in this case, just run `ssh-keygen -R "mail.example.org"` as recommended. chown echobot: -R /run/echobot ``` -4. Now, update DNS to the new IP addresses. +4. Now, update DNS entries. - If other servers try to deliver messages to your server they may fail, - but normally email servers will retry delivering messages + 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 server. - Your users will be able to use the chatmail server as soon as the DNS changes have propagated. - VoilĂ ! +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 server does not depend on the client IP address +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 server +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 server to VPS +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 server +to forward connections to the chatmail relay 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 +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 server still needs +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 server, +for your chatmail relay, put the following configuration in `/etc/nftables.conf`: ``` #!/usr/sbin/nft -f @@ -454,7 +457,7 @@ define wan = eth0 # Which ports to proxy. # # Note that SSH is not proxied -# so it is possible to log into the proxy server +# so it is possible to log into the proxy server # and not the original one. define ports = { smtp, http, https, imap, imaps, submission, submissions } @@ -517,7 +520,7 @@ table inet filter { ``` Run `systemctl enable nftables.service` -to ensure configuration is reloaded when the proxy server reboots. +to ensure configuration is reloaded when the proxy relay reboots. Uncomment in `/etc/sysctl.conf` the following two lines: @@ -526,7 +529,7 @@ 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`. +Then reboot the relay or do `sysctl -p` and `nft -f /etc/nftables.conf`. -Once proxy server is set up, +Once proxy relay is set up, you can add its IP address to the DNS. From 5ba99dc78214808d0e95b86e7e4c37b974b7eef3 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Wed, 2 Apr 2025 16:41:01 +0200 Subject: [PATCH 04/27] shorten first title to fit in one line in default layout --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 957a1ec..dd59804 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# Chatmail relays for end-to-end encrypted instant e-mail +# Chatmail relays for end-to-end encrypted e-mail Chatmail relay servers are interoperable Mail Transport Agents (MTAs) designed for: From 7578c5f1d374001f9c7fb38d1ddc99062caff0c6 Mon Sep 17 00:00:00 2001 From: missytake Date: Mon, 7 Apr 2025 10:00:33 +0200 Subject: [PATCH 05/27] chore: add issue template --- .github/ISSUE_TEMPLATE/bug_report.md | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md 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 + From b0434dc9274485c8ea23c55ceace7e3849a50238 Mon Sep 17 00:00:00 2001 From: missytake Date: Mon, 7 Apr 2025 10:01:52 +0200 Subject: [PATCH 06/27] chore: add blank issues + the mutual help chat group --- .github/ISSUE_TEMPLATE/config.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/config.yml diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..85489c1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Mutual Help Chat Group + url: + about: If you have troubles setting up the relay server, feel free to ask here. From 04ae0b86fbb53ac5162e9feee359e8a8b99184dc Mon Sep 17 00:00:00 2001 From: missytake Date: Tue, 8 Apr 2025 10:39:57 +0200 Subject: [PATCH 07/27] added invite link to mutual help group --- .github/ISSUE_TEMPLATE/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 85489c1..f04681f 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: true contact_links: - name: Mutual Help Chat Group - url: + 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. From 49787044ffccd647d7d3d1857b22da6d6f61b7ea Mon Sep 17 00:00:00 2001 From: link2xt Date: Mon, 7 Apr 2025 20:55:58 +0000 Subject: [PATCH 08/27] Do not encourage non-random addresses and weak passwords --- www/src/info.md | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/www/src/info.md b/www/src/info.md index 3556249..e12f528 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 From c848b6134682979dc8676e34145b00cb70980dbb Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Tue, 8 Apr 2025 14:57:00 +0200 Subject: [PATCH 09/27] add a hint that deletion may be earlier there is another mention of times in privacy.md, however, there the gist is about that things are deleted, it is fine if that happens earlier there (also it is not excluded). targets discussion from https://github.com/chatmail/relay/pull/504 --- www/src/info.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/www/src/info.md b/www/src/info.md index e12f528..1fd7eb5 100644 --- a/www/src/info.md +++ b/www/src/info.md @@ -15,10 +15,11 @@ for the usage in chats, especially DeltaChat. - 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 From 3cc9bc3ceb19a2fb50cdb6e721dd686b54f3f795 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Wed, 9 Apr 2025 16:09:17 +0200 Subject: [PATCH 10/27] avoid initial runs to show acmetool not found errors --- cmdeploy/src/cmdeploy/remote/rshell.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 From 9c381e1fbf918c9ad8a993fd9b04b30df9a26c3b Mon Sep 17 00:00:00 2001 From: missytake Date: Wed, 9 Apr 2025 17:40:52 +0200 Subject: [PATCH 11/27] added changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa18c8e..e709597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## untagged +- Avoid "acmetool not found" during initial run + ([#550](https://github.com/chatmail/relay/pull/550)) + - 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. From b45be700a8f3239f7dc63c175cdcbcaf7a609256 Mon Sep 17 00:00:00 2001 From: missytake Date: Sat, 29 Mar 2025 08:47:05 +0100 Subject: [PATCH 12/27] cmdeploy: disable nsd so it doesn't block port 53 --- cmdeploy/src/cmdeploy/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cmdeploy/src/cmdeploy/__init__.py b/cmdeploy/src/cmdeploy/__init__.py index e12c53c..d60f882 100644 --- a/cmdeploy/src/cmdeploy/__init__.py +++ b/cmdeploy/src/cmdeploy/__init__.py @@ -588,6 +588,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. + systemd.service( + name="Disable nsd if it's running, so it doesn't block port 53", + service="nsd.service", + running=False, + enabled=False, + ) apt.packages( name="Install unbound", packages=["unbound", "unbound-anchor", "dnsutils"], From f9e885c44286b0d969f2884fb5446a96859b6939 Mon Sep 17 00:00:00 2001 From: missytake Date: Sat, 29 Mar 2025 08:50:44 +0100 Subject: [PATCH 13/27] doc: add changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e709597..b83b0a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ - Enforce end-to-end encryption between local addresses ([#535](https://github.com/chatmail/server/pull/535)) +- Disable NSD so it doesn't block port 53 + ([#537](https://github.com/chatmail/server/pull/537)) + - 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)) From 21f9885ffe08addcdc5d83d0912acf88438c5967 Mon Sep 17 00:00:00 2001 From: missytake Date: Thu, 10 Apr 2025 11:44:54 +0200 Subject: [PATCH 14/27] unbound: check that 53 is not occupied by a different process --- CHANGELOG.md | 2 +- cmdeploy/src/cmdeploy/__init__.py | 29 ++++++++++++++++++++++------- cmdeploy/src/cmdeploy/cmdeploy.py | 20 ++++++++++++-------- 3 files changed, 35 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b83b0a3..73af289 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ - Enforce end-to-end encryption between local addresses ([#535](https://github.com/chatmail/server/pull/535)) -- Disable NSD so it doesn't block port 53 +- unbound: check that port 53 is not occupied by a different process ([#537](https://github.com/chatmail/server/pull/537)) - Limit the bind for the HTTPS server on 8443 to 127.0.0.1 diff --git a/cmdeploy/src/cmdeploy/__init__.py b/cmdeploy/src/cmdeploy/__init__.py index d60f882..0ac35ff 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(): @@ -230,7 +246,6 @@ def _configure_opendkim(domain: str, dkim_selector: str = "dkim") -> bool: ) need_restart |= service_file.changed - return need_restart @@ -588,12 +603,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. - systemd.service( - name="Disable nsd if it's running, so it doesn't block port 53", - service="nsd.service", - running=False, - enabled=False, - ) + 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 3904e1d..5918773 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 From aa4259477fe838cdea759ecd896b6462f7e790c2 Mon Sep 17 00:00:00 2001 From: Mark Felder Date: Wed, 2 Apr 2025 11:52:43 -0700 Subject: [PATCH 15/27] Postfix master.cf: use 127.0.0.1 for consistency --- cmdeploy/src/cmdeploy/postfix/master.cf.j2 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmdeploy/src/cmdeploy/postfix/master.cf.j2 b/cmdeploy/src/cmdeploy/postfix/master.cf.j2 index 3573da7..49c745d 100644 --- a/cmdeploy/src/cmdeploy/postfix/master.cf.j2 +++ b/cmdeploy/src/cmdeploy/postfix/master.cf.j2 @@ -77,13 +77,13 @@ scache unix - - y - 1 scache postlog unix-dgram n - n - 1 postlogd filter unix - n n - - lmtp # Local SMTP server for reinjecting outgoing filtered mail. -localhost:{{ config.postfix_reinject_port }} inet n - n - 10 smtpd +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 incoming filtered mail -localhost:{{ config.postfix_reinject_port_incoming }} inet n - n - 10 smtpd +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 From c9078d7c927f4a8bb02880849b62528465737f14 Mon Sep 17 00:00:00 2001 From: missytake Date: Thu, 10 Apr 2025 11:51:26 +0200 Subject: [PATCH 16/27] doc: add changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73af289..9eba808 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,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)) From 9f74d0a608bceaa77c254a337a0027f57c3ca393 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Thu, 10 Apr 2025 16:20:24 +0200 Subject: [PATCH 17/27] cleanly time out trying to connect to port 25 and treat failure as "skip" not real failure. --- CHANGELOG.md | 3 +++ cmdeploy/src/cmdeploy/tests/online/test_0_login.py | 7 ++++++- cmdeploy/src/cmdeploy/tests/online/test_1_basic.py | 7 ++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eba808..11b73ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## untagged +- 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)) 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..fe449e0 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py @@ -118,7 +118,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) From 71160b8f6509a7ecd26e726c98b1332768e7500e Mon Sep 17 00:00:00 2001 From: holger krekel Date: Thu, 10 Apr 2025 16:50:45 +0200 Subject: [PATCH 18/27] fix timezone handling such that client/server do not need to have the same --- CHANGELOG.md | 4 ++++ cmdeploy/src/cmdeploy/tests/online/test_1_basic.py | 11 ++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11b73ec..2bfbacc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ - 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. diff --git a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py index fe449e0..a1dd0bf 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 * 24 def test_remote(remote, imap_or_smtp): From 44ff6da5d2b37c26cb5c66f2935149a20dd64c87 Mon Sep 17 00:00:00 2001 From: missytake Date: Tue, 11 Mar 2025 11:59:26 +0100 Subject: [PATCH 19/27] DNS: add 9.9.9.9 to resolv.conf if unbound isn't there yet --- CHANGELOG.md | 3 +++ cmdeploy/src/cmdeploy/__init__.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bfbacc..909f918 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,9 @@ - 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)) diff --git a/cmdeploy/src/cmdeploy/__init__.py b/cmdeploy/src/cmdeploy/__init__.py index 0ac35ff..91d8921 100644 --- a/cmdeploy/src/cmdeploy/__init__.py +++ b/cmdeploy/src/cmdeploy/__init__.py @@ -592,6 +592,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) From 1fba4a3cdf86efd225d9adbc7fdbcc75fcfb1fe7 Mon Sep 17 00:00:00 2001 From: missytake Date: Thu, 10 Apr 2025 23:26:38 +0200 Subject: [PATCH 20/27] tests: check whether opendkim restarted in the last 48 hours --- cmdeploy/src/cmdeploy/tests/online/test_1_basic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py index a1dd0bf..c1bb4bb 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py @@ -60,7 +60,7 @@ class TestSSHExecutor: 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 * 24 + assert (now - since_date).total_seconds() < 60 * 60 * 48 def test_remote(remote, imap_or_smtp): From 046552061e5ae7934a57bdf0bd11dbb4fa013a17 Mon Sep 17 00:00:00 2001 From: missytake Date: Fri, 11 Apr 2025 00:28:42 +0200 Subject: [PATCH 21/27] tests: maximum diff between timezones is 27h, +24h --- cmdeploy/src/cmdeploy/tests/online/test_1_basic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py index c1bb4bb..e2f1903 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py @@ -60,7 +60,7 @@ class TestSSHExecutor: 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 * 48 + assert (now - since_date).total_seconds() < 60 * 60 * 51 def test_remote(remote, imap_or_smtp): From a0a1dd65a664a91fa4cd8441f8f33dfda364f8c0 Mon Sep 17 00:00:00 2001 From: missytake Date: Fri, 11 Apr 2025 12:21:53 +0200 Subject: [PATCH 22/27] release v1.6.0 --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 909f918..da2c4b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## untagged + +## 1.6.0 2025-04-11 + - Handle Port-25 connect errors more gracefully (common with VPNs) ([#552](https://github.com/chatmail/relay/pull/552)) From a78c9035217af2fd1899ce7fdc0db7fc0dc13c7e Mon Sep 17 00:00:00 2001 From: missytake Date: Fri, 11 Apr 2025 15:00:04 +0200 Subject: [PATCH 23/27] cmdeploy: config value for deleting large messages after X days --- CHANGELOG.md | 2 ++ chatmaild/src/chatmaild/config.py | 1 + chatmaild/src/chatmaild/ini/chatmail.ini.f | 3 +++ chatmaild/src/chatmaild/tests/test_config.py | 1 + cmdeploy/src/cmdeploy/dovecot/expunge.cron.j2 | 2 +- cmdeploy/src/cmdeploy/tests/online/test_1_basic.py | 2 ++ 6 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da2c4b4..117e479 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## untagged +- 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 diff --git a/chatmaild/src/chatmaild/config.py b/chatmaild/src/chatmaild/config.py index 8edb192..971906b 100644 --- a/chatmaild/src/chatmaild/config.py +++ b/chatmaild/src/chatmaild/config.py @@ -26,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"]) diff --git a/chatmaild/src/chatmaild/ini/chatmail.ini.f b/chatmaild/src/chatmaild/ini/chatmail.ini.f index d9e5261..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 diff --git a/chatmaild/src/chatmaild/tests/test_config.py b/chatmaild/src/chatmaild/tests/test_config.py index 542084a..6ef3c61 100644 --- a/chatmaild/src/chatmaild/tests/test_config.py +++ b/chatmaild/src/chatmaild/tests/test_config.py @@ -35,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/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/tests/online/test_1_basic.py b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py index e2f1903..6ab9690 100644 --- a/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py +++ b/cmdeploy/src/cmdeploy/tests/online/test_1_basic.py @@ -182,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 From 1d4aa3d20514f1f0de1af9b4d0a1dfad22a17635 Mon Sep 17 00:00:00 2001 From: s0ph0s Date: Wed, 16 Apr 2025 15:06:41 -0400 Subject: [PATCH 24/27] Add note to README about related projects --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index dd59804..737c0f1 100644 --- a/README.md +++ b/README.md @@ -533,3 +533,12 @@ 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. From 5f29c53232ae652c84f594d1e5c9bd632b036c21 Mon Sep 17 00:00:00 2001 From: link2xt Date: Wed, 23 Apr 2025 16:59:26 +0000 Subject: [PATCH 25/27] Fix mox URL in the README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 737c0f1..7dbf592 100644 --- a/README.md +++ b/README.md @@ -538,7 +538,7 @@ you can add its IP address to the DNS. Here are some related projects that you may be interested in: -- [Mox](https://github.com/-mjl/mox): A Golang email server. [Work is 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. From b9a4471ee417cd1f4ee6e429f1e9fd24fc26961e Mon Sep 17 00:00:00 2001 From: missytake Date: Sun, 20 Apr 2025 21:17:51 +0200 Subject: [PATCH 26/27] cmdeploy: run apt update to make sure dns-utils can be installed --- CHANGELOG.md | 3 +++ cmdeploy/src/cmdeploy/remote/rdns.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 117e479..210ee73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 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)) 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}") From ab9ec98bcc1826fc212601c31aa6bff99815b742 Mon Sep 17 00:00:00 2001 From: Adon Metcalfe Date: Sat, 26 Apr 2025 10:39:13 +0800 Subject: [PATCH 27/27] Update README.md minor doc fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7dbf592..5c1c080 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ This repository has four directories: 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`) +`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.