email_handler.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. """
  2. Handle the email *forward* and *reply*. phase. There are 3 actors:
  3. - website: who sends emails to alias@sl.co address
  4. - SL email handler (this script)
  5. - user personal email: to be protected. Should never leak to website.
  6. This script makes sure that in the forward phase, the email that is forwarded to user personal email has the following
  7. envelope and header fields:
  8. Envelope:
  9. mail from: @website
  10. rcpt to: @personal_email
  11. Header:
  12. From: @website
  13. To: alias@sl.co # so user knows this email is sent to alias
  14. Reply-to: special@sl.co # magic HERE
  15. And in the reply phase:
  16. Envelope:
  17. mail from: @website
  18. rcpt to: @website
  19. Header:
  20. From: alias@sl.co # so for website the email comes from alias. magic HERE
  21. To: @website
  22. The special@sl.co allows to hide user personal email when user clicks "Reply" to the forwarded email.
  23. It should contain the following info:
  24. - alias
  25. - @website
  26. """
  27. import time
  28. from email.message import Message
  29. from email.parser import Parser
  30. from email.policy import SMTPUTF8
  31. from smtplib import SMTP
  32. from aiosmtpd.controller import Controller
  33. from app.config import EMAIL_DOMAIN, POSTFIX_SERVER, URL, ALIAS_DOMAINS
  34. from app.email_utils import (
  35. get_email_name,
  36. get_email_part,
  37. send_email,
  38. add_dkim_signature,
  39. get_email_domain_part,
  40. add_or_replace_header,
  41. delete_header,
  42. send_cannot_create_directory_alias,
  43. send_cannot_create_domain_alias,
  44. email_belongs_to_alias_domains,
  45. send_reply_alias_must_use_personal_email,
  46. )
  47. from app.extensions import db
  48. from app.log import LOG
  49. from app.models import GenEmail, ForwardEmail, ForwardEmailLog, CustomDomain, Directory
  50. from app.utils import random_string
  51. from server import create_app
  52. # fix the database connection leak issue
  53. # use this method instead of create_app
  54. def new_app():
  55. app = create_app()
  56. @app.teardown_appcontext
  57. def shutdown_session(response_or_exc):
  58. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  59. db.session.remove()
  60. # dispose the engine too
  61. db.engine.dispose()
  62. return app
  63. class MailHandler:
  64. async def handle_DATA(self, server, session, envelope):
  65. LOG.debug(">>> New message <<<")
  66. LOG.debug("Mail from %s", envelope.mail_from)
  67. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  68. message_data = envelope.content.decode("utf8", errors="replace")
  69. # Only when debug
  70. # LOG.debug("Message data:\n")
  71. # LOG.debug(message_data)
  72. # host IP, setup via Docker network
  73. smtp = SMTP(POSTFIX_SERVER, 25)
  74. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  75. rcpt_to = envelope.rcpt_tos[0].lower()
  76. # Reply case
  77. # reply+ or ra+ (reverse-alias) prefix
  78. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  79. LOG.debug("Reply phase")
  80. app = new_app()
  81. with app.app_context():
  82. return self.handle_reply(envelope, smtp, msg)
  83. else: # Forward case
  84. LOG.debug("Forward phase")
  85. app = new_app()
  86. with app.app_context():
  87. return self.handle_forward(envelope, smtp, msg)
  88. def handle_forward(self, envelope, smtp: SMTP, msg: Message) -> str:
  89. """return *status_code message*"""
  90. alias = envelope.rcpt_tos[0].lower() # alias@SL
  91. gen_email = GenEmail.get_by(email=alias)
  92. if not gen_email:
  93. LOG.d(
  94. "alias %s not exist. Try to see if it can be created on the fly", alias
  95. )
  96. # try to see if alias could be created on-the-fly
  97. on_the_fly = False
  98. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  99. if email_belongs_to_alias_domains(alias):
  100. if "/" in alias or "+" in alias or "#" in alias:
  101. if "/" in alias:
  102. sep = "/"
  103. elif "+" in alias:
  104. sep = "+"
  105. else:
  106. sep = "#"
  107. directory_name = alias[: alias.find(sep)]
  108. LOG.d("directory_name %s", directory_name)
  109. directory = Directory.get_by(name=directory_name)
  110. # Only premium user can use the directory feature
  111. if directory:
  112. dir_user = directory.user
  113. if dir_user.is_premium():
  114. LOG.d("create alias %s for directory %s", alias, directory)
  115. on_the_fly = True
  116. gen_email = GenEmail.create(
  117. email=alias,
  118. user_id=directory.user_id,
  119. directory_id=directory.id,
  120. )
  121. db.session.commit()
  122. else:
  123. LOG.error(
  124. "User %s is not premium anymore and cannot create alias with directory",
  125. dir_user,
  126. )
  127. send_cannot_create_directory_alias(
  128. dir_user, alias, directory_name
  129. )
  130. # try to create alias on-the-fly with custom-domain catch-all feature
  131. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  132. if not on_the_fly:
  133. alias_domain = get_email_domain_part(alias)
  134. custom_domain = CustomDomain.get_by(domain=alias_domain)
  135. # Only premium user can continue using the catch-all feature
  136. if custom_domain and custom_domain.catch_all:
  137. domain_user = custom_domain.user
  138. if domain_user.is_premium():
  139. LOG.d("create alias %s for domain %s", alias, custom_domain)
  140. on_the_fly = True
  141. gen_email = GenEmail.create(
  142. email=alias,
  143. user_id=custom_domain.user_id,
  144. custom_domain_id=custom_domain.id,
  145. automatic_creation=True,
  146. )
  147. db.session.commit()
  148. else:
  149. LOG.error(
  150. "User %s is not premium anymore and cannot create alias with domain %s",
  151. domain_user,
  152. alias_domain,
  153. )
  154. send_cannot_create_domain_alias(
  155. domain_user, alias, alias_domain
  156. )
  157. if not on_the_fly:
  158. LOG.d("alias %s cannot be created on-the-fly, return 510", alias)
  159. return "510 Email not exist"
  160. user_email = gen_email.user.email
  161. website_email = get_email_part(msg["From"])
  162. forward_email = ForwardEmail.get_by(
  163. gen_email_id=gen_email.id, website_email=website_email
  164. )
  165. if not forward_email:
  166. LOG.debug(
  167. "create forward email for alias %s and website email %s",
  168. alias,
  169. website_email,
  170. )
  171. # generate a reply_email, make sure it is unique
  172. # not use while to avoid infinite loop
  173. for _ in range(1000):
  174. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  175. if not ForwardEmail.get_by(reply_email=reply_email):
  176. break
  177. forward_email = ForwardEmail.create(
  178. gen_email_id=gen_email.id,
  179. website_email=website_email,
  180. website_from=msg["From"],
  181. reply_email=reply_email,
  182. )
  183. db.session.commit()
  184. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  185. if gen_email.enabled:
  186. # add custom header
  187. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  188. # remove reply-to header if present
  189. delete_header(msg, "Reply-To")
  190. # change the from header so the sender comes from @SL
  191. # so it can pass DMARC check
  192. # replace the email part in from: header
  193. from_header = (
  194. get_email_name(msg["From"])
  195. + " - "
  196. + website_email.replace("@", " at ")
  197. + f" <{forward_email.reply_email}>"
  198. )
  199. msg.replace_header("From", from_header)
  200. LOG.d("new from header:%s", from_header)
  201. # add List-Unsubscribe header
  202. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  203. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  204. add_or_replace_header(
  205. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  206. )
  207. add_dkim_signature(msg, EMAIL_DOMAIN)
  208. LOG.d(
  209. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  210. website_email,
  211. user_email,
  212. envelope.mail_options,
  213. envelope.rcpt_options,
  214. )
  215. # smtp.send_message has UnicodeEncodeErroremail issue
  216. # encode message raw directly instead
  217. msg_raw = msg.as_string().encode()
  218. smtp.sendmail(
  219. forward_email.reply_email,
  220. user_email,
  221. msg_raw,
  222. envelope.mail_options,
  223. envelope.rcpt_options,
  224. )
  225. else:
  226. LOG.d("%s is disabled, do not forward", gen_email)
  227. forward_log.blocked = True
  228. db.session.commit()
  229. return "250 Message accepted for delivery"
  230. def handle_reply(self, envelope, smtp: SMTP, msg: Message) -> str:
  231. reply_email = envelope.rcpt_tos[0].lower()
  232. # reply_email must end with EMAIL_DOMAIN
  233. if not reply_email.endswith(EMAIL_DOMAIN):
  234. LOG.error(f"Reply email {reply_email} has wrong domain")
  235. return "550 wrong reply email"
  236. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  237. alias: str = forward_email.gen_email.email
  238. alias_domain = alias[alias.find("@") + 1 :]
  239. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  240. if not email_belongs_to_alias_domains(alias):
  241. if not CustomDomain.get_by(domain=alias_domain):
  242. return "550 alias unknown by SimpleLogin"
  243. user_email = forward_email.gen_email.user.email
  244. if envelope.mail_from.lower() != user_email.lower():
  245. LOG.error(
  246. f"Reply email can only be used by user email. Actual mail_from: %s. User email %s. reply_email %s",
  247. envelope.mail_from,
  248. user_email,
  249. reply_email,
  250. )
  251. send_reply_alias_must_use_personal_email(
  252. forward_email.gen_email.user,
  253. forward_email.gen_email.email,
  254. envelope.mail_from,
  255. )
  256. send_email(
  257. envelope.mail_from,
  258. f"Your email ({envelope.mail_from}) is not allowed to send email to {reply_email}",
  259. "",
  260. "",
  261. )
  262. return "550 ignored"
  263. delete_header(msg, "DKIM-Signature")
  264. # the email comes from alias
  265. msg.replace_header("From", alias)
  266. # some email providers like ProtonMail adds automatically the Reply-To field
  267. # make sure to delete it
  268. delete_header(msg, "Reply-To")
  269. msg.replace_header("To", forward_email.website_email)
  270. # add List-Unsubscribe header
  271. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  272. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  273. add_or_replace_header(
  274. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  275. )
  276. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  277. delete_header(msg, "Received-SPF")
  278. LOG.d(
  279. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  280. alias,
  281. forward_email.website_email,
  282. envelope.mail_options,
  283. envelope.rcpt_options,
  284. )
  285. if alias_domain in ALIAS_DOMAINS:
  286. add_dkim_signature(msg, alias_domain)
  287. # add DKIM-Signature for custom-domain alias
  288. else:
  289. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  290. if custom_domain.dkim_verified:
  291. add_dkim_signature(msg, alias_domain)
  292. msg_raw = msg.as_string().encode()
  293. smtp.sendmail(
  294. alias,
  295. forward_email.website_email,
  296. msg_raw,
  297. envelope.mail_options,
  298. envelope.rcpt_options,
  299. )
  300. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  301. db.session.commit()
  302. return "250 Message accepted for delivery"
  303. if __name__ == "__main__":
  304. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  305. controller.start()
  306. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  307. while True:
  308. time.sleep(2)