email_handler.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 typing import Optional
  33. from aiosmtpd.controller import Controller
  34. from app.config import (
  35. EMAIL_DOMAIN,
  36. POSTFIX_SERVER,
  37. URL,
  38. ALIAS_DOMAINS,
  39. ADMIN_EMAIL,
  40. SUPPORT_EMAIL,
  41. )
  42. from app.email_utils import (
  43. get_email_name,
  44. get_email_part,
  45. send_email,
  46. add_dkim_signature,
  47. get_email_domain_part,
  48. add_or_replace_header,
  49. delete_header,
  50. send_cannot_create_directory_alias,
  51. send_cannot_create_domain_alias,
  52. email_belongs_to_alias_domains,
  53. render,
  54. )
  55. from app.extensions import db
  56. from app.log import LOG
  57. from app.models import (
  58. GenEmail,
  59. ForwardEmail,
  60. ForwardEmailLog,
  61. CustomDomain,
  62. Directory,
  63. User,
  64. DeletedAlias,
  65. )
  66. from app.utils import random_string
  67. from server import create_app
  68. # fix the database connection leak issue
  69. # use this method instead of create_app
  70. def new_app():
  71. app = create_app()
  72. @app.teardown_appcontext
  73. def shutdown_session(response_or_exc):
  74. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  75. db.session.remove()
  76. # dispose the engine too
  77. db.engine.dispose()
  78. return app
  79. def try_auto_create(alias: str) -> Optional[GenEmail]:
  80. """Try to auto-create the alias using directory or catch-all domain
  81. """
  82. gen_email = try_auto_create_catch_all_domain(alias)
  83. if not gen_email:
  84. gen_email = try_auto_create_directory(alias)
  85. return gen_email
  86. def try_auto_create_directory(alias: str) -> Optional[GenEmail]:
  87. """
  88. Try to create an alias with directory
  89. """
  90. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  91. if email_belongs_to_alias_domains(alias):
  92. # if there's no directory separator in the alias, no way to auto-create it
  93. if "/" not in alias and "+" not in alias and "#" not in alias:
  94. return None
  95. # alias contains one of the 3 special directory separator: "/", "+" or "#"
  96. if "/" in alias:
  97. sep = "/"
  98. elif "+" in alias:
  99. sep = "+"
  100. else:
  101. sep = "#"
  102. directory_name = alias[: alias.find(sep)]
  103. LOG.d("directory_name %s", directory_name)
  104. directory = Directory.get_by(name=directory_name)
  105. if not directory:
  106. return None
  107. dir_user: User = directory.user
  108. if not dir_user.can_create_new_alias():
  109. send_cannot_create_directory_alias(dir_user, alias, directory_name)
  110. return None
  111. # if alias has been deleted before, do not auto-create it
  112. if DeletedAlias.get_by(email=alias, user_id=directory.user_id):
  113. LOG.error(
  114. "Alias %s was deleted before, cannot auto-create using directory %s, user %s",
  115. alias,
  116. directory_name,
  117. dir_user,
  118. )
  119. return None
  120. LOG.d("create alias %s for directory %s", alias, directory)
  121. gen_email = GenEmail.create(
  122. email=alias, user_id=directory.user_id, directory_id=directory.id,
  123. )
  124. db.session.commit()
  125. return gen_email
  126. def try_auto_create_catch_all_domain(alias: str) -> Optional[GenEmail]:
  127. """Try to create an alias with catch-all domain"""
  128. # try to create alias on-the-fly with custom-domain catch-all feature
  129. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  130. alias_domain = get_email_domain_part(alias)
  131. custom_domain = CustomDomain.get_by(domain=alias_domain)
  132. if not custom_domain:
  133. return None
  134. # custom_domain exists
  135. if not custom_domain.catch_all:
  136. return None
  137. # custom_domain has catch-all enabled
  138. domain_user: User = custom_domain.user
  139. if not domain_user.can_create_new_alias():
  140. send_cannot_create_domain_alias(domain_user, alias, alias_domain)
  141. return None
  142. # if alias has been deleted before, do not auto-create it
  143. if DeletedAlias.get_by(email=alias, user_id=custom_domain.user_id):
  144. LOG.error(
  145. "Alias %s was deleted before, cannot auto-create using domain catch-all %s, user %s",
  146. alias,
  147. custom_domain,
  148. domain_user,
  149. )
  150. return None
  151. LOG.d("create alias %s for domain %s", alias, custom_domain)
  152. gen_email = GenEmail.create(
  153. email=alias,
  154. user_id=custom_domain.user_id,
  155. custom_domain_id=custom_domain.id,
  156. automatic_creation=True,
  157. )
  158. db.session.commit()
  159. return gen_email
  160. def get_or_create_forward_email(
  161. website_from_header: str, gen_email: GenEmail
  162. ) -> ForwardEmail:
  163. """
  164. website_from_header can be the full-form email, i.e. "First Last <email@example.com>"
  165. """
  166. website_email = get_email_part(website_from_header)
  167. forward_email = ForwardEmail.get_by(
  168. gen_email_id=gen_email.id, website_email=website_email
  169. )
  170. if forward_email:
  171. # update the website_from if needed
  172. if forward_email.website_from != website_from_header:
  173. LOG.d("Update From header for %s", forward_email)
  174. forward_email.website_from = website_from_header
  175. db.session.commit()
  176. else:
  177. LOG.debug(
  178. "create forward email for alias %s and website email %s",
  179. gen_email,
  180. website_from_header,
  181. )
  182. # generate a reply_email, make sure it is unique
  183. # not use while loop to avoid infinite loop
  184. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  185. for _ in range(1000):
  186. if not ForwardEmail.get_by(reply_email=reply_email):
  187. # found!
  188. break
  189. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  190. forward_email = ForwardEmail.create(
  191. gen_email_id=gen_email.id,
  192. website_email=website_email,
  193. website_from=website_from_header,
  194. reply_email=reply_email,
  195. )
  196. db.session.commit()
  197. return forward_email
  198. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  199. """return *status_code message*"""
  200. alias = rcpt_to.lower() # alias@SL
  201. gen_email = GenEmail.get_by(email=alias)
  202. if not gen_email:
  203. LOG.d("alias %s not exist. Try to see if it can be created on the fly", alias)
  204. gen_email = try_auto_create(alias)
  205. if not gen_email:
  206. LOG.d("alias %s cannot be created on-the-fly, return 510", alias)
  207. return "510 Email not exist"
  208. if gen_email.mailbox_id:
  209. mailbox_email = gen_email.mailbox.email
  210. else:
  211. mailbox_email = gen_email.user.email
  212. forward_email = get_or_create_forward_email(msg["From"], gen_email)
  213. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  214. if gen_email.enabled:
  215. # add custom header
  216. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  217. # remove reply-to header if present
  218. delete_header(msg, "Reply-To")
  219. # change the from header so the sender comes from @SL
  220. # so it can pass DMARC check
  221. # replace the email part in from: header
  222. website_from_header = msg["From"]
  223. website_email = get_email_part(website_from_header)
  224. from_header = (
  225. get_email_name(website_from_header)
  226. + ("" if get_email_name(website_from_header) == "" else " - ")
  227. + website_email.replace("@", " at ")
  228. + f" <{forward_email.reply_email}>"
  229. )
  230. msg.replace_header("From", from_header)
  231. LOG.d("new from header:%s", from_header)
  232. # add List-Unsubscribe header
  233. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  234. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  235. add_or_replace_header(
  236. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  237. )
  238. add_dkim_signature(msg, EMAIL_DOMAIN)
  239. LOG.d(
  240. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  241. website_email,
  242. mailbox_email,
  243. envelope.mail_options,
  244. envelope.rcpt_options,
  245. )
  246. # smtp.send_message has UnicodeEncodeErroremail issue
  247. # encode message raw directly instead
  248. msg_raw = msg.as_string().encode()
  249. smtp.sendmail(
  250. forward_email.reply_email,
  251. mailbox_email,
  252. msg_raw,
  253. envelope.mail_options,
  254. envelope.rcpt_options,
  255. )
  256. else:
  257. LOG.d("%s is disabled, do not forward", gen_email)
  258. forward_log.blocked = True
  259. db.session.commit()
  260. return "250 Message accepted for delivery"
  261. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  262. reply_email = rcpt_to.lower()
  263. # reply_email must end with EMAIL_DOMAIN
  264. if not reply_email.endswith(EMAIL_DOMAIN):
  265. LOG.warning(f"Reply email {reply_email} has wrong domain")
  266. return "550 wrong reply email"
  267. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  268. if not forward_email:
  269. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  270. return "550 wrong reply email"
  271. alias: str = forward_email.gen_email.email
  272. alias_domain = alias[alias.find("@") + 1 :]
  273. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  274. if not email_belongs_to_alias_domains(alias):
  275. if not CustomDomain.get_by(domain=alias_domain):
  276. return "550 alias unknown by SimpleLogin"
  277. gen_email = forward_email.gen_email
  278. if gen_email.mailbox_id:
  279. mailbox_email = gen_email.mailbox.email
  280. else:
  281. mailbox_email = gen_email.user.email
  282. # bounce email initiated by Postfix
  283. # can happen in case emails cannot be delivered to user-email
  284. # in this case Postfix will try to send a bounce report to original sender, which is
  285. # the "reply email"
  286. if envelope.mail_from == "<>":
  287. LOG.error(
  288. "Bounce when sending to alias %s, user %s, from header: %s",
  289. alias,
  290. gen_email.user,
  291. msg["From"],
  292. )
  293. # send the bounce email payload to admin
  294. msg.replace_header("From", SUPPORT_EMAIL)
  295. msg.replace_header("To", ADMIN_EMAIL)
  296. add_dkim_signature(msg, get_email_domain_part(SUPPORT_EMAIL))
  297. smtp.sendmail(
  298. SUPPORT_EMAIL,
  299. ADMIN_EMAIL,
  300. msg.as_string().encode(),
  301. envelope.mail_options,
  302. envelope.rcpt_options,
  303. )
  304. return "550 ignored"
  305. # only mailbox can send email to the reply-email
  306. if envelope.mail_from.lower() != mailbox_email.lower():
  307. LOG.warning(
  308. f"Reply email can only be used by user email. Actual mail_from: %s. msg from header: %s, User email %s. reply_email %s",
  309. envelope.mail_from,
  310. msg["From"],
  311. mailbox_email,
  312. reply_email,
  313. )
  314. user = gen_email.user
  315. send_email(
  316. mailbox_email,
  317. f"Reply from your alias {alias} only works from your mailbox",
  318. render(
  319. "transactional/reply-must-use-personal-email.txt",
  320. name=user.name,
  321. alias=alias,
  322. sender=envelope.mail_from,
  323. mailbox_email=mailbox_email,
  324. ),
  325. render(
  326. "transactional/reply-must-use-personal-email.html",
  327. name=user.name,
  328. alias=alias,
  329. sender=envelope.mail_from,
  330. mailbox_email=mailbox_email,
  331. ),
  332. )
  333. # Notify sender that they cannot send emails to this address
  334. send_email(
  335. envelope.mail_from,
  336. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  337. render(
  338. "transactional/send-from-alias-from-unknown-sender.txt",
  339. sender=envelope.mail_from,
  340. reply_email=reply_email,
  341. ),
  342. "",
  343. )
  344. return "550 ignored"
  345. delete_header(msg, "DKIM-Signature")
  346. # the email comes from alias
  347. msg.replace_header("From", alias)
  348. # some email providers like ProtonMail adds automatically the Reply-To field
  349. # make sure to delete it
  350. delete_header(msg, "Reply-To")
  351. msg.replace_header("To", forward_email.website_email)
  352. # add List-Unsubscribe header
  353. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  354. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  355. add_or_replace_header(msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
  356. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  357. delete_header(msg, "Received-SPF")
  358. LOG.d(
  359. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  360. alias,
  361. forward_email.website_email,
  362. envelope.mail_options,
  363. envelope.rcpt_options,
  364. )
  365. if alias_domain in ALIAS_DOMAINS:
  366. add_dkim_signature(msg, alias_domain)
  367. # add DKIM-Signature for custom-domain alias
  368. else:
  369. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  370. if custom_domain.dkim_verified:
  371. add_dkim_signature(msg, alias_domain)
  372. msg_raw = msg.as_string().encode()
  373. smtp.sendmail(
  374. alias,
  375. forward_email.website_email,
  376. msg_raw,
  377. envelope.mail_options,
  378. envelope.rcpt_options,
  379. )
  380. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  381. db.session.commit()
  382. return "250 Message accepted for delivery"
  383. class MailHandler:
  384. async def handle_DATA(self, server, session, envelope):
  385. LOG.debug(">>> New message <<<")
  386. LOG.debug("Mail from %s", envelope.mail_from)
  387. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  388. message_data = envelope.content.decode("utf8", errors="replace")
  389. smtp = SMTP(POSTFIX_SERVER, 25)
  390. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  391. for rcpt_to in envelope.rcpt_tos:
  392. # Reply case
  393. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  394. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  395. LOG.debug("Reply phase")
  396. app = new_app()
  397. with app.app_context():
  398. return handle_reply(envelope, smtp, msg, rcpt_to)
  399. else: # Forward case
  400. LOG.debug("Forward phase")
  401. app = new_app()
  402. with app.app_context():
  403. return handle_forward(envelope, smtp, msg, rcpt_to)
  404. if __name__ == "__main__":
  405. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  406. controller.start()
  407. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  408. while True:
  409. time.sleep(2)