email_handler.py 14 KB

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