Compare commits

..

20 Commits

Author SHA1 Message Date
link2xt
1cdc5d1351 Revert "open a persistent client between the BeforeQueueHandler and postfix smtpd without content filter"
This reverts commit fb2ea27477.
2023-10-19 02:22:38 +00:00
link2xt
30680cb170 filtermail: port is args[0], not args[1] 2023-10-19 02:22:30 +00:00
link2xt
c514fb00a3 Import SMTP from aiosmtpd.lmtp, not aiosmtpd.smtp 2023-10-19 02:22:15 +00:00
holger krekel
c7995356b9 shift for simpler diff 2023-10-19 01:16:19 +02:00
holger krekel
fb2ea27477 open a persistent client between the BeforeQueueHandler and postfix smtpd without content filter 2023-10-19 01:10:06 +02:00
holger krekel
7cf6cc2c91 remove filtermail split and LMTP backend 2023-10-19 01:05:49 +02:00
holger krekel
4358d5fe61 only do a smtp beforequeue-handler, also simplifies the send-rate-limiting test and improves DC behaviour 2023-10-19 00:54:45 +02:00
holger krekel
10cb099c0e all tests pass 2023-10-19 00:07:22 +02:00
holger krekel
bbd2773506 refactor test and filtermail to prepare it for BeforeQueue handling 2023-10-18 21:43:06 +02:00
missytake
410bc50a8b test: report if rate limit from last test was still active 2023-10-18 19:02:40 +02:00
missytake
015269fa7b test: test that there is no internal limit (xfail for now) 2023-10-18 19:02:40 +02:00
missytake
b8673d8625 postfix: add simple rate limiting without allow list or leaky bucket, also for internal mail 2023-10-18 19:02:40 +02:00
missytake
31c71fa6e9 add test for postfix rate limiting 2023-10-18 19:02:40 +02:00
holger krekel
8fcd423015 apply most of linkxt review comments 2023-10-18 18:59:01 +02:00
holger krekel
df39d05263 doc the test 2023-10-18 18:59:01 +02:00
holger krekel
05ce4f769b make test more readable 2023-10-18 18:59:01 +02:00
holger krekel
8dc05ba7ec also test that external addresses fail to be forged 2023-10-18 18:59:01 +02:00
holger krekel
6701c9749c refactor test to be more strict 2023-10-18 18:59:01 +02:00
holger krekel
c6d8f7e759 initial forged-from protection 2023-10-18 18:59:01 +02:00
link2xt
76765164dc Deploy nginx and autoconfig XML 2023-10-18 18:32:28 +02:00
12 changed files with 264 additions and 147 deletions

View File

@@ -1,12 +1,14 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
import logging import logging
import time
import sys
from email.parser import BytesParser from email.parser import BytesParser
from email import policy from email import policy
from email.utils import parseaddr from email.utils import parseaddr
from aiosmtpd.lmtp import LMTP from aiosmtpd.smtp import SMTP
from aiosmtpd.controller import UnixSocketController from aiosmtpd.controller import Controller
from smtplib import SMTP as SMTPClient from smtplib import SMTP as SMTPClient
@@ -32,94 +34,93 @@ def check_encrypted(message):
return True return True
class ExampleController(UnixSocketController): class SMTPController(Controller):
def factory(self): def factory(self):
return LMTP(self.handler, **self.SMTP_kwargs) return SMTP(self.handler, **self.SMTP_kwargs)
class ExampleHandler: class BeforeQueueHandler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options): def __init__(self):
envelope.rcpt_tos.append(address) self.send_rate_limiter = SendRateLimiter()
async def handle_MAIL(self, server, session, envelope, address, mail_options):
logging.info(f"handle_MAIL from {address}")
envelope.mail_from = address
if not self.send_rate_limiter.is_sending_allowed(address):
return f"450 4.7.1: Too much mail from {address}"
parts = envelope.mail_from.split("@")
if len(parts) != 2:
return f"500 Invalid from address <{envelope.mail_from!r}>"
return "250 OK" return "250 OK"
async def handle_DATA(self, server, session, envelope): async def handle_DATA(self, server, session, envelope):
valid_recipients, res = lmtp_handle_DATA(envelope) logging.info("handle_DATA before-queue")
# Reinject the mail back into Postfix. error = check_DATA(envelope)
if valid_recipients: if error:
logging.info("Reinjecting the mail") return error
client = SMTPClient("localhost", "10026") logging.info("re-injecting the mail that passed checks")
client.sendmail(envelope.mail_from, valid_recipients, envelope.content) client = SMTPClient("localhost", "10025")
else: client.sendmail(envelope.mail_from, envelope.rcpt_tos, envelope.content)
logging.info("no valid recipients, ignoring mail") return "250 OK"
return "\r\n".join(res)
async def asyncmain(loop): async def asyncmain_beforequeue(port):
controller = ExampleController( Controller(BeforeQueueHandler(), hostname="127.0.0.1", port=port).start()
ExampleHandler(), unix_socket="/var/spool/postfix/private/filtermail"
)
controller.start()
def lmtp_handle_DATA(envelope): def check_DATA(envelope):
"""the central filtering function for e-mails.""" """the central filtering function for e-mails."""
logging.info(f"Processing DATA message from {envelope.mail_from}") logging.info(f"Processing DATA message from {envelope.mail_from}")
message = BytesParser(policy=policy.default).parsebytes(envelope.content) message = BytesParser(policy=policy.default).parsebytes(envelope.content)
mail_encrypted = check_encrypted(message) mail_encrypted = check_encrypted(message)
valid_recipients = [] _, from_addr = parseaddr(message.get("from").strip())
res = [] 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}>"
envelope_from_domain = from_addr.split("@").pop()
for recipient in envelope.rcpt_tos: for recipient in envelope.rcpt_tos:
my_local_domain = envelope.mail_from.split("@")
if len(my_local_domain) != 2:
res += [f"500 Invalid from address <{envelope.mail_from}>"]
continue
_, from_addr = parseaddr(message.get("from").strip())
logging.info(f"mime-from: {from_addr} envelope-from: {envelope.mail_from}")
if envelope.mail_from.lower() != from_addr.lower():
res += [f"500 Invalid FROM <{from_addr}> for <{envelope.mail_from}>"]
continue
if envelope.mail_from == recipient: if envelope.mail_from == recipient:
# Always allow sending emails to self. # Always allow sending emails to self.
valid_recipients += [recipient]
res += ["250 OK"]
continue continue
res = recipient.split("@")
if len(res) != 2:
return f"500 Invalid address <{recipient}>"
_recipient_addr, recipient_domain = res
recipient_local_domain = recipient.split("@") is_outgoing = recipient_domain != envelope_from_domain
if len(recipient_local_domain) != 2: if is_outgoing and not mail_encrypted:
res += [f"500 Invalid address <{recipient}>"] is_securejoin = message.get("secure-join") in ["vc-request", "vg-request"]
continue if not is_securejoin:
return f"500 Invalid unencrypted mail to <{recipient}>"
is_outgoing = recipient_local_domain[1] != my_local_domain[1]
if ( class SendRateLimiter:
is_outgoing MAX_USER_SEND_PER_MINUTE = 80
and not mail_encrypted
and message.get("secure-join") != "vc-request"
and message.get("secure-join") != "vg-request"
):
res += ["500 Outgoing mail must be encrypted"]
continue
valid_recipients += [recipient] def __init__(self):
res += ["250 OK"] self.addr2timestamps = {}
assert len(envelope.rcpt_tos) == len(res) def is_sending_allowed(self, mail_from):
assert len(valid_recipients) <= len(res) last = self.addr2timestamps.setdefault(mail_from, [])
return valid_recipients, res now = time.time()
last[:] = [ts for ts in last if ts >= (now - 60)]
if len(last) <= self.MAX_USER_SEND_PER_MINUTE:
last.append(now)
return True
return False
def main(): def main():
args = sys.argv[1:]
assert len(args) == 1
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
loop = asyncio.new_event_loop() loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
loop.create_task(asyncmain(loop=loop)) task = asyncmain_beforequeue(port=int(args[0]))
loop.create_task(task)
loop.run_forever() loop.run_forever()
if __name__ == "__main__":
main()

View File

@@ -1,8 +1,8 @@
[Unit] [Unit]
Description=Email filter for chatmail servers Description=Chatmail Postfix BeforeQeue filter
[Service] [Service]
ExecStart=/usr/local/bin/filtermail ExecStart=/usr/local/bin/filtermail 10080
Restart=always Restart=always
RestartSec=30 RestartSec=30

View File

@@ -1,6 +1,7 @@
from .filtermail import check_encrypted, lmtp_handle_DATA from .filtermail import check_encrypted, check_DATA, SendRateLimiter
from email.parser import BytesParser from email.parser import BytesParser
from email import policy from email import policy
import pytest
def test_reject_forged_from(): def test_reject_forged_from():
@@ -30,15 +31,12 @@ def test_reject_forged_from():
# test that the filter lets good mail through # test that the filter lets good mail through
envelope.content = makemail(envelope.mail_from).as_bytes() envelope.content = makemail(envelope.mail_from).as_bytes()
valid_recipients, res = lmtp_handle_DATA(envelope=envelope) assert not check_DATA(envelope=envelope)
assert valid_recipients == envelope.rcpt_tos
assert len(res) == 1 and "250" in res[0]
# test that the filter rejects forged mail # test that the filter rejects forged mail
envelope.content = makemail("forged@c3.testrun.org").as_bytes() envelope.content = makemail("forged@c3.testrun.org").as_bytes()
valid_recipients, res = lmtp_handle_DATA(envelope=envelope) error = check_DATA(envelope=envelope)
assert not valid_recipients assert "500" in error
assert len(res) == 1 and "500" in res[0]
def test_filtermail(): def test_filtermail():
@@ -326,3 +324,15 @@ def test_filtermail():
] ]
).encode() ).encode()
) )
def test_send_rate_limiter():
limiter = SendRateLimiter()
for i in range(100):
if limiter.is_sending_allowed("some@example.org"):
if i <= SendRateLimiter.MAX_USER_SEND_PER_MINUTE:
continue
pytest.fail("limiter didn't work")
else:
assert i == SendRateLimiter.MAX_USER_SEND_PER_MINUTE + 1
break

View File

@@ -34,43 +34,28 @@ def _install_chatmaild() -> None:
commands=[f"pip install --break-system-packages {remote_path}"], commands=[f"pip install --break-system-packages {remote_path}"],
) )
files.put( for fn in (
name="upload doveauth-dictproxy.service", "doveauth-dictproxy",
src=importlib.resources.files("chatmaild") "filtermail",
.joinpath("doveauth-dictproxy.service") ):
.open("rb"), files.put(
dest="/etc/systemd/system/doveauth-dictproxy.service", name=f"Upload {fn}.service",
user="root", src=importlib.resources.files("chatmaild")
group="root", .joinpath(f"{fn}.service")
mode="644", .open("rb"),
) dest=f"/etc/systemd/system/{fn}.service",
systemd.service( user="root",
name="Setup doveauth-dictproxy service", group="root",
service="doveauth-dictproxy.service", mode="644",
running=True, )
enabled=True, systemd.service(
restarted=True, name=f"Setup {fn} service",
daemon_reload=True, service=f"{fn}.service",
) running=True,
enabled=True,
files.put( restarted=True,
name="upload filtermail.service", daemon_reload=True,
src=importlib.resources.files("chatmaild") )
.joinpath("filtermail.service")
.open("rb"),
dest="/etc/systemd/system/filtermail.service",
user="root",
group="root",
mode="644",
)
systemd.service(
name="Setup filtermail service",
service="filtermail.service",
running=True,
enabled=True,
restarted=True,
daemon_reload=True,
)
def _configure_opendkim(domain: str, dkim_selector: str) -> bool: def _configure_opendkim(domain: str, dkim_selector: str) -> bool:
@@ -173,6 +158,33 @@ def _configure_dovecot(mail_server: str, debug: bool = False) -> bool:
return need_restart return need_restart
def _configure_nginx(domain: str, debug: bool = False) -> bool:
"""Configures nginx HTTP server."""
need_restart = False
main_config = files.template(
src=importlib.resources.files(__package__).joinpath("nginx.conf.j2"),
dest="/etc/nginx/nginx.conf",
user="root",
group="root",
mode="644",
config={"domain_name": domain},
)
need_restart |= main_config.changed
autoconfig = files.template(
src=importlib.resources.files(__package__).joinpath("autoconfig.xml.j2"),
dest="/var/www/html/.well-known/autoconfig/mail/config-v1.1.xml",
user="root",
group="root",
mode="644",
config={"domain_name": domain},
)
need_restart |= autoconfig.changed
return need_restart
def deploy_chatmail(mail_domain: str, mail_server: str, dkim_selector: str) -> None: def deploy_chatmail(mail_domain: str, mail_server: str, dkim_selector: str) -> None:
"""Deploy a chat-mail instance. """Deploy a chat-mail instance.
@@ -194,7 +206,7 @@ def deploy_chatmail(mail_domain: str, mail_server: str, dkim_selector: str) -> N
) )
# Deploy acmetool to have TLS certificates. # Deploy acmetool to have TLS certificates.
deploy_acmetool(domains=[mail_server]) deploy_acmetool(nginx_hook=True, domains=[mail_server])
apt.packages( apt.packages(
name="Install Postfix", name="Install Postfix",
@@ -214,11 +226,17 @@ def deploy_chatmail(mail_domain: str, mail_server: str, dkim_selector: str) -> N
], ],
) )
apt.packages(
name="Install nginx",
packages=["nginx"],
)
_install_chatmaild() _install_chatmaild()
debug = False debug = False
dovecot_need_restart = _configure_dovecot(mail_server, debug=debug) dovecot_need_restart = _configure_dovecot(mail_server, debug=debug)
postfix_need_restart = _configure_postfix(mail_domain, debug=debug) postfix_need_restart = _configure_postfix(mail_domain, debug=debug)
opendkim_need_restart = _configure_opendkim(mail_domain, dkim_selector) opendkim_need_restart = _configure_opendkim(mail_domain, dkim_selector)
nginx_need_restart = _configure_nginx(mail_domain)
systemd.service( systemd.service(
name="Start and enable OpenDKIM", name="Start and enable OpenDKIM",
@@ -244,6 +262,14 @@ def deploy_chatmail(mail_domain: str, mail_server: str, dkim_selector: str) -> N
restarted=dovecot_need_restart, restarted=dovecot_need_restart,
) )
systemd.service(
name="Start and enable nginx",
service="nginx.service",
running=True,
enabled=True,
restarted=nginx_need_restart,
)
# This file is used by auth proxy. # This file is used by auth proxy.
# https://wiki.debian.org/EtcMailName # https://wiki.debian.org/EtcMailName
server.shell( server.shell(

View File

@@ -38,22 +38,13 @@ def deploy_acmetool(nginx_hook=False, email="", domains=[]):
email=email, email=email,
) )
service_file = files.put( files.template(
src=importlib.resources.files(__package__) src=importlib.resources.files(__package__).joinpath("target.yaml.j2"),
.joinpath("acmetool-redirector.service") dest="/var/lib/acme/conf/target",
.open("rb"),
dest="/etc/systemd/system/acmetool-redirector.service",
user="root", user="root",
group="root", group="root",
mode="644", mode="644",
) )
systemd.service(
name="Setup acmetool-redirector service",
service="acmetool-redirector.service",
running=False,
enabled=False,
restarted=service_file.changed,
)
for domain in domains: for domain in domains:
server.shell( server.shell(

View File

@@ -1,11 +0,0 @@
[Unit]
Description=acmetool HTTP redirector
[Service]
Type=notify
ExecStart=/usr/bin/acmetool redirector --service.uid=daemon
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,7 @@
request:
provider: https://acme-v02.api.letsencrypt.org/directory
key:
type: rsa
challenge:
webroot-paths:
- /var/www/html/.well-known/acme-challenge

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<clientConfig version="1.1">
<emailProvider id="{{ config.domain_name }}">
<domain>{{ config.domain_name }}</domain>
<displayName>{{ config.domain_name }} chatmail</displayName>
<displayShortName>{{ config.domain_name }}</displayShortName>
<incomingServer type="imap">
<hostname>{{ config.domain_name }}</hostname>
<port>993</port>
<socketType>SSL</socketType>
<authentication>password-cleartext</authentication>
<username>%EMAILADDRESS%</username>
</incomingServer>
<incomingServer type="imap">
<hostname>{{ config.domain_name }}</hostname>
<port>143</port>
<socketType>STARTTLS</socketType>
<authentication>password-cleartext</authentication>
<username>%EMAILADDRESS%</username>
</incomingServer>
<outgoingServer type="smtp">
<hostname>{{ config.domain_name }}</hostname>
<port>465</port>
<socketType>SSL</socketType>
<authentication>password-cleartext</authentication>
<username>%EMAILADDRESS%</username>
</outgoingServer>
<outgoingServer type="smtp">
<hostname>{{ config.domain_name }}</hostname>
<port>587</port>
<socketType>STARTTLS</socketType>
<authentication>password-cleartext</authentication>
<username>%EMAILADDRESS%</username>
</outgoingServer>
</emailProvider>
</clientConfig>

View File

@@ -0,0 +1,47 @@
user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
events {
worker_connections 768;
# multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
# Do not emit nginx version on error pages.
server_tokens off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_certificate /var/lib/acme/live/{{ config.domain_name }}/fullchain;
ssl_certificate_key /var/lib/acme/live/{{ config.domain_name }}/privkey;
gzip on;
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
}

View File

@@ -32,7 +32,7 @@ submission inet n - y - - smtpd
-o smtpd_recipient_restrictions= -o smtpd_recipient_restrictions=
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING -o milter_macro_daemon_name=ORIGINATING
-o content_filter=filter:unix:private/filtermail -o smtpd_proxy_filter=127.0.0.1:10080
smtps inet n - y - - smtpd smtps inet n - y - - smtpd
-o syslog_name=postfix/smtps -o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes -o smtpd_tls_wrappermode=yes
@@ -47,7 +47,7 @@ smtps inet n - y - - smtpd
-o smtpd_recipient_restrictions= -o smtpd_recipient_restrictions=
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING -o milter_macro_daemon_name=ORIGINATING
-o content_filter=filter:unix:private/filtermail -o smtpd_proxy_filter=127.0.0.1:10080
#628 inet n - y - - qmqpd #628 inet n - y - - qmqpd
pickup unix n - y 60 1 pickup pickup unix n - y 60 1 pickup
cleanup unix n - y - 0 cleanup cleanup unix n - y - 0 cleanup
@@ -76,5 +76,5 @@ scache unix - - y - 1 scache
postlog unix-dgram n - n - 1 postlogd postlog unix-dgram n - n - 1 postlogd
filter unix - n n - - lmtp filter unix - n n - - lmtp
# Local SMTP server for reinjecting filered mail. # Local SMTP server for reinjecting filered mail.
localhost:10026 inet n - n - 10 smtpd localhost:10025 inet n - n - 10 smtpd
-o content_filter= -o content_filter=

View File

@@ -20,7 +20,7 @@ def test_use_two_chatmailservers(cmfactory, maildomain2):
@pytest.mark.parametrize("forgeaddr", ["internal", "someone@example.org"]) @pytest.mark.parametrize("forgeaddr", ["internal", "someone@example.org"])
def test_reject_forged_from(cmsetup, mailgen, lp, remote, forgeaddr): def test_reject_forged_from(cmsetup, mailgen, lp, forgeaddr):
user1, user3 = cmsetup.gen_users(2) user1, user3 = cmsetup.gen_users(2)
lp.sec("send encrypted message with forged from") lp.sec("send encrypted message with forged from")
@@ -36,17 +36,25 @@ def test_reject_forged_from(cmsetup, mailgen, lp, remote, forgeaddr):
print(f" {line}") print(f" {line}")
lp.sec("Send forged mail and check remote postfix lmtp processing result") lp.sec("Send forged mail and check remote postfix lmtp processing result")
remote_log = remote.iter_output("journalctl -t postfix/lmtp") with pytest.raises(smtplib.SMTPException) as e:
user1.smtp.sendmail(from_addr=user1.addr, to_addrs=[user3.addr], msg=msg) user1.smtp.sendmail(from_addr=user1.addr, to_addrs=[user3.addr], msg=msg)
for line in remote_log: assert "500" in str(e.value)
# print(line)
if "500 invalid from" in line and user3.addr in line:
break
else:
pytest.fail("remote postfix/filtermail failed to reject message")
# check that the logged in user (who sent the forged msg) got a non-delivery notice
for message in user1.imap.fetch_all_messages(): @pytest.mark.slow
if "Invalid FROM" in message and addr_to_forge in message: def test_exceed_rate_limit(cmsetup, gencreds, mailgen):
"""Test that the per-account send-mail limit is exceeded."""
user1, user2 = cmsetup.gen_users(2)
mail = mailgen.get_encrypted(user1.addr, user2.addr)
for i in range(100):
print("Sending mail", str(i))
try:
user1.smtp.sendmail(user1.addr, [user2.addr], mail)
except smtplib.SMTPException as e:
if i < 80:
pytest.fail(f"rate limit was exceeded too early with msg {i}")
outcome = e.recipients[user2.addr]
assert outcome[0] == 450
assert b'4.7.1: Too much mail from' in outcome[1]
return return
pytest.fail(f"forged From={addr_to_forge} did not cause non-delivery notice") pytest.fail("Rate limit was not exceeded")

View File

@@ -1,4 +1,5 @@
import pytest import pytest
import smtplib
def test_login_basic_functioning(imap_or_smtp, gencreds, lp): def test_login_basic_functioning(imap_or_smtp, gencreds, lp):