Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
email_server: Attempt to reject unauth'd destinations at RCPT TO time.
Alex Vandiver01e08f0e324e
diff --git a/zerver/lib/email_mirror.py b/zerver/lib/email_mirror.pyindex bc2382543db..78e0b929b08 100644--- a/zerver/lib/email_mirror.py+++ b/zerver/lib/email_mirror.py@@ -413,6 +413,22 @@ def is_forwarded(subject: str) -> bool:return bool(re.match(reg, subject, flags=re.IGNORECASE))+def check_access_for_channel_email_address(channel_email_address: ChannelEmailAddress) -> None:+ channel = channel_email_address.channel+ sender = channel_email_address.sender+ creator = channel_email_address.creator+ realm = channel_email_address.realm+ email_gateway_bot = get_system_bot(settings.EMAIL_GATEWAY_BOT, realm.id)++ if sender.id == email_gateway_bot.id and creator is not None:+ user_for_access_check = creator+ else:+ user_for_access_check = sender++ # Raises JsonableError on permission denied+ access_stream_for_send_message(user_for_access_check, channel, forwarder_user_profile=None)++def process_stream_message(to: str, message: EmailMessage) -> None:subject_header = message.get("Subject", "")@@ -428,28 +444,19 @@ def process_stream_message(to: str, message: EmailMessage) -> None:subject = subject or _("Email with no subject")channel_email_address, options = decode_stream_email_address(to)-- # Don't remove quotations if message is forwarded, unless otherwise specified:- if "include_quotes" not in options:- options["include_quotes"] = is_forwarded(subject_header)-channel = channel_email_address.channelsender = channel_email_address.sender- creator = channel_email_address.creatorrealm = channel_email_address.realm- email_gateway_bot = get_system_bot(settings.EMAIL_GATEWAY_BOT, realm.id)-- if sender.id == email_gateway_bot.id and creator is not None:- user_for_access_check = creator- else:- user_for_access_check = sender-try:- access_stream_for_send_message(user_for_access_check, channel, forwarder_user_profile=None)+ check_access_for_channel_email_address(channel_email_address)except JsonableError as e:logger.info("Failed to process email to %s (%s): %s", channel.name, realm.string_id, e)return+ # Don't remove quotations if message is forwarded, unless otherwise specified:+ if "include_quotes" not in options:+ options["include_quotes"] = is_forwarded(subject_header)+body = construct_zulip_body(message, realm, sender=sender, **options)send_zulip(sender, channel, subject, body)logger.info(@@ -523,11 +530,28 @@ def process_message(message: EmailMessage, rcpt_to: str | None = None) -> None:log_error(message, e.args[0], to)-def validate_to_address(rcpt_to: str) -> None:- if is_missed_message_address(rcpt_to):- get_usable_missed_message_address(rcpt_to)+def validate_to_address(address: str, rate_limit: bool = True) -> None:+ if is_missed_message_address(address):+ mm_address = get_usable_missed_message_address(address)+ if mm_address.message.recipient.type == Recipient.STREAM:+ # ACL's on DMs are harder to apply simply, so we+ # just check channel messages.+ access_stream_for_send_message(+ mm_address.user_profile,+ get_stream_by_id_in_realm(+ mm_address.message.recipient.type_id,+ mm_address.user_profile.realm,+ ),+ forwarder_user_profile=None,+ )else:- decode_stream_email_address(rcpt_to)+ channel_email = decode_stream_email_address(address)[0]+ if rate_limit:+ # Only channel email addresses are rate-limited, since+ # they are likely to be used as the destination for+ # mails from automated systems.+ rate_limit_mirror_by_realm(channel_email.realm)+ check_access_for_channel_email_address(channel_email)# Email mirror rate limiter code:diff --git a/zerver/lib/email_mirror_server.py b/zerver/lib/email_mirror_server.pyindex 008d63f3c2b..2b69c907957 100644--- a/zerver/lib/email_mirror_server.py+++ b/zerver/lib/email_mirror_server.py@@ -22,17 +22,12 @@ from django.core.mail import EmailMultiAlternatives as DjangoEmailMultiAlternatifrom typing_extensions import overridefrom version import ZULIP_VERSION-from zerver.lib.email_mirror import (- decode_stream_email_address,- is_missed_message_address,- rate_limit_mirror_by_realm,- validate_to_address,-)+from zerver.lib.email_mirror import decode_stream_email_address, validate_to_addressfrom zerver.lib.email_mirror_helpers import (ZulipEmailForwardError,get_email_gateway_message_string_from_address,)-from zerver.lib.exceptions import RateLimitedError+from zerver.lib.exceptions import JsonableError, RateLimitedErrorfrom zerver.lib.logging_util import log_to_filefrom zerver.lib.queue import queue_json_publish_rollback_unsafe@@ -96,27 +91,28 @@ class ZulipMessageHandler(MessageHandler):return "250 Continue"try:+ # Attempt to do the ACL-check now, just to reject early.+ # The authoritative check is done in the worker, but we+ # wish to reject now if we can do so simply.await sync_to_async(validate_to_address)(address)- if not is_missed_message_address(address):- # Only channel email addresses are rate-limited, since- # they are likely to be used as the destination for- # mails from automated systems.- recipient_realm = await sync_to_async(- lambda a: decode_stream_email_address(a)[0].realm- )(address)- try:- rate_limit_mirror_by_realm(recipient_realm)- except RateLimitedError:- logger.warning(- "Rejecting a MAIL FROM: %s to realm: %s - rate limited.",- envelope.mail_from,- recipient_realm.name,- )- return "550 4.7.0 Rate-limited due to too many emails on this realm."++ except RateLimitedError:+ recipient_realm = await sync_to_async(+ lambda a: decode_stream_email_address(a)[0].realm+ )(address)+ logger.warning(+ "Rejecting a MAIL FROM: %s to realm: %s - rate limited.",+ envelope.mail_from,+ recipient_realm.name,+ )+ return "550 4.7.0 Rate-limited due to too many emails on this realm."except ZulipEmailForwardError as e:return f"550 5.1.1 Bad destination mailbox address: {e}"+ except JsonableError as e:+ return f"550 5.7.1 Permission denied: {e}"+envelope.rcpt_tos.append(address)return "250 Continue"diff --git a/zerver/management/commands/send_to_email_mirror.py b/zerver/management/commands/send_to_email_mirror.pyindex f1e32334f06..1c114163a90 100644--- a/zerver/management/commands/send_to_email_mirror.py+++ b/zerver/management/commands/send_to_email_mirror.py@@ -101,7 +101,7 @@ Example:self._prepare_message(message, realm, stream, creator, sender)rcpt_to = message["To"].addresses[0].addr_spec- validate_to_address(rcpt_to)+ validate_to_address(rcpt_to, rate_limit=False)queue_json_publish_rollback_unsafe("email_mirror",diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex eb27ce11f9c..3209a1b296f 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -2202,6 +2202,36 @@ class TestEmailMirrorServer(ZulipTestCase):],)+ @override_settings(EMAIL_GATEWAY_PATTERN="%[email protected]")+ async def test_handler_missedmessage_denied(self) -> None:+ hamlet = await sync_to_async(lambda: self.example_user("hamlet"))()+ othello = await sync_to_async(lambda: self.example_user("othello"))()+ await sync_to_async(lambda: self.send_stream_message(hamlet, "Denmark", "Some message"))()+ mm_address = await sync_to_async(+ lambda: create_missed_message_address(othello, most_recent_message(othello))+ )()+ # Deactivate the stream so the mail bounces+ await sync_to_async(+ lambda: do_deactivate_stream(get_stream("Denmark", othello.realm), acting_user=None)+ )()+ self.assertEqual(+ await self.handler_response(+ [+ "HELO localhost",+ "MAIL FROM: <[email protected]>",+ f"RCPT TO: <{mm_address}>",+ "QUIT",+ ]+ ),+ [+ "220 testhost Zulip 1.2.3\r\n",+ "250 testhost\r\n",+ "250 OK\r\n",+ "550 5.7.1 Permission denied: Not authorized to send to channel 'Denmark'\r\n",+ "221 Bye\r\n",+ ],+ )+@override_settings(EMAIL_GATEWAY_PATTERN="%[email protected]")async def test_handler_missedmessage(self) -> None:othello = await sync_to_async(lambda: self.example_user("othello"))()@@ -2258,6 +2288,69 @@ class TestEmailMirrorServer(ZulipTestCase):@override_settings(EMAIL_GATEWAY_PATTERN="%[email protected]")async def test_handler_stream(self) -> None:+ stream_name = "some str"+ realm = await sync_to_async(lambda: get_realm("zulip"))()+ stream = await sync_to_async(lambda: ensure_stream(realm, stream_name, acting_user=None))()+ hamlet = await sync_to_async(lambda: self.example_user("hamlet"))()+ email_gateway_bot = await sync_to_async(+ lambda: get_system_bot(settings.EMAIL_GATEWAY_BOT, realm.id)+ )()+ for sender in (hamlet, email_gateway_bot):+ email_token = await sync_to_async(+ lambda sender: get_channel_email_token(stream, creator=hamlet, sender=sender)+ )(sender)+ email_address = encode_email_address(stream.name, email_token)+ with mock.patch(+ "zerver.lib.email_mirror_server.queue_json_publish_rollback_unsafe"+ ) as m:+ self.assertEqual(+ await self.handler_response(+ [+ "HELO localhost",+ "MAIL FROM: <[email protected]>",+ f"RCPT TO: <{email_address}>",+ "DATA",+ f"From: {hamlet.delivery_email}",+ f"To: {email_address}",+ "Subject: Stream message",+ "",+ "Some body!",+ ".",+ "QUIT",+ ]+ ),+ [+ "220 testhost Zulip 1.2.3\r\n",+ "250 testhost\r\n",+ "250 OK\r\n",+ "250 Continue\r\n",+ "354 End data with <CR><LF>.<CR><LF>\r\n",+ "250 OK\r\n",+ "221 Bye\r\n",+ ],+ )+ message_lines = (+ f"From: {hamlet.delivery_email}",+ f"To: {email_address}",+ "Subject: Stream message",+ "X-Peer: other-host:1234",+ "X-MailFrom: [email protected]",+ f"X-RcptTo: {email_address}",+ "",+ "Some body!",+ )+ m.assert_called_once_with(+ "email_mirror",+ {+ "rcpt_to": email_address,+ "msg_base64": base64.b64encode(+ b"".join([line.encode() + b"\n" for line in message_lines])+ ).decode(),+ },+ )++ @override_settings(EMAIL_GATEWAY_PATTERN="%[email protected]")+ async def test_handler_stream_deactivated(self) -> None:stream_name = "some str"realm = await sync_to_async(lambda: get_realm("zulip"))()stream = await sync_to_async(lambda: ensure_stream(realm, stream_name, acting_user=None))()@@ -2266,49 +2359,24 @@ class TestEmailMirrorServer(ZulipTestCase):lambda: get_channel_email_token(stream, creator=hamlet, sender=hamlet))()email_address = encode_email_address(stream.name, email_token)- with mock.patch("zerver.lib.email_mirror_server.queue_json_publish_rollback_unsafe") as m:- self.assertEqual(- await self.handler_response(- [- "HELO localhost",- "MAIL FROM: <[email protected]>",- f"RCPT TO: <{email_address}>",- "DATA",- f"From: {hamlet.delivery_email}",- f"To: {email_address}",- "Subject: Stream message",- "",- "Some body!",- ".",- "QUIT",- ]- ),++ # Deactivate the stream so the mail bounces+ await sync_to_async(lambda: do_deactivate_stream(stream, acting_user=None))()++ self.assertEqual(+ await self.handler_response([- "220 testhost Zulip 1.2.3\r\n",- "250 testhost\r\n",- "250 OK\r\n",- "250 Continue\r\n",- "354 End data with <CR><LF>.<CR><LF>\r\n",- "250 OK\r\n",- "221 Bye\r\n",- ],- )- message_lines = (- f"From: {hamlet.delivery_email}",- f"To: {email_address}",- "Subject: Stream message",- "X-Peer: other-host:1234",- "X-MailFrom: [email protected]",- f"X-RcptTo: {email_address}",- "",- "Some body!",- )- m.assert_called_once_with(- "email_mirror",- {- "rcpt_to": email_address,- "msg_base64": base64.b64encode(- b"".join([line.encode() + b"\n" for line in message_lines])- ).decode(),- },- )+ "HELO localhost",+ "MAIL FROM: <[email protected]>",+ f"RCPT TO: <{email_address}>",+ "QUIT",+ ]+ ),+ [+ "220 testhost Zulip 1.2.3\r\n",+ "250 testhost\r\n",+ "250 OK\r\n",+ "550 5.7.1 Permission denied: Not authorized to send to channel 'some str'\r\n",+ "221 Bye\r\n",+ ],+ )