email_handler.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. import uuid
  29. from email import encoders
  30. from email.message import Message
  31. from email.mime.application import MIMEApplication
  32. from email.mime.multipart import MIMEMultipart
  33. from email.parser import Parser
  34. from email.policy import SMTPUTF8
  35. from email.utils import parseaddr, formataddr
  36. from io import BytesIO
  37. from smtplib import SMTP
  38. from typing import Optional
  39. from aiosmtpd.controller import Controller
  40. from app import pgp_utils, s3
  41. from app.config import (
  42. EMAIL_DOMAIN,
  43. POSTFIX_SERVER,
  44. URL,
  45. ALIAS_DOMAINS,
  46. POSTFIX_SUBMISSION_TLS,
  47. )
  48. from app.email_utils import (
  49. get_email_part,
  50. send_email,
  51. add_dkim_signature,
  52. get_email_domain_part,
  53. add_or_replace_header,
  54. delete_header,
  55. send_cannot_create_directory_alias,
  56. send_cannot_create_domain_alias,
  57. email_belongs_to_alias_domains,
  58. render,
  59. get_orig_message_from_bounce,
  60. delete_all_headers_except,
  61. )
  62. from app.extensions import db
  63. from app.log import LOG
  64. from app.models import (
  65. GenEmail,
  66. ForwardEmail,
  67. ForwardEmailLog,
  68. CustomDomain,
  69. Directory,
  70. User,
  71. DeletedAlias,
  72. RefusedEmail,
  73. )
  74. from app.utils import random_string
  75. from server import create_app
  76. # fix the database connection leak issue
  77. # use this method instead of create_app
  78. def new_app():
  79. app = create_app()
  80. @app.teardown_appcontext
  81. def shutdown_session(response_or_exc):
  82. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  83. db.session.remove()
  84. # dispose the engine too
  85. db.engine.dispose()
  86. return app
  87. def try_auto_create(alias: str) -> Optional[GenEmail]:
  88. """Try to auto-create the alias using directory or catch-all domain
  89. """
  90. gen_email = try_auto_create_catch_all_domain(alias)
  91. if not gen_email:
  92. gen_email = try_auto_create_directory(alias)
  93. return gen_email
  94. def try_auto_create_directory(alias: str) -> Optional[GenEmail]:
  95. """
  96. Try to create an alias with directory
  97. """
  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 there's no directory separator in the alias, no way to auto-create it
  101. if "/" not in alias and "+" not in alias and "#" not in alias:
  102. return None
  103. # alias contains one of the 3 special directory separator: "/", "+" or "#"
  104. if "/" in alias:
  105. sep = "/"
  106. elif "+" in alias:
  107. sep = "+"
  108. else:
  109. sep = "#"
  110. directory_name = alias[: alias.find(sep)]
  111. LOG.d("directory_name %s", directory_name)
  112. directory = Directory.get_by(name=directory_name)
  113. if not directory:
  114. return None
  115. dir_user: User = directory.user
  116. if not dir_user.can_create_new_alias():
  117. send_cannot_create_directory_alias(dir_user, alias, directory_name)
  118. return None
  119. # if alias has been deleted before, do not auto-create it
  120. if DeletedAlias.get_by(email=alias, user_id=directory.user_id):
  121. LOG.warning(
  122. "Alias %s was deleted before, cannot auto-create using directory %s, user %s",
  123. alias,
  124. directory_name,
  125. dir_user,
  126. )
  127. return None
  128. LOG.d("create alias %s for directory %s", alias, directory)
  129. gen_email = GenEmail.create(
  130. email=alias,
  131. user_id=directory.user_id,
  132. directory_id=directory.id,
  133. mailbox_id=dir_user.default_mailbox_id,
  134. )
  135. db.session.commit()
  136. return gen_email
  137. def try_auto_create_catch_all_domain(alias: str) -> Optional[GenEmail]:
  138. """Try to create an alias with catch-all domain"""
  139. # try to create alias on-the-fly with custom-domain catch-all feature
  140. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  141. alias_domain = get_email_domain_part(alias)
  142. custom_domain = CustomDomain.get_by(domain=alias_domain)
  143. if not custom_domain:
  144. return None
  145. # custom_domain exists
  146. if not custom_domain.catch_all:
  147. return None
  148. # custom_domain has catch-all enabled
  149. domain_user: User = custom_domain.user
  150. if not domain_user.can_create_new_alias():
  151. send_cannot_create_domain_alias(domain_user, alias, alias_domain)
  152. return None
  153. # if alias has been deleted before, do not auto-create it
  154. if DeletedAlias.get_by(email=alias, user_id=custom_domain.user_id):
  155. LOG.warning(
  156. "Alias %s was deleted before, cannot auto-create using domain catch-all %s, user %s",
  157. alias,
  158. custom_domain,
  159. domain_user,
  160. )
  161. return None
  162. LOG.d("create alias %s for domain %s", alias, custom_domain)
  163. gen_email = GenEmail.create(
  164. email=alias,
  165. user_id=custom_domain.user_id,
  166. custom_domain_id=custom_domain.id,
  167. automatic_creation=True,
  168. mailbox_id=domain_user.default_mailbox_id,
  169. )
  170. db.session.commit()
  171. return gen_email
  172. def get_or_create_forward_email(
  173. website_from_header: str, gen_email: GenEmail
  174. ) -> ForwardEmail:
  175. """
  176. website_from_header can be the full-form email, i.e. "First Last <email@example.com>"
  177. """
  178. website_email = get_email_part(website_from_header)
  179. forward_email = ForwardEmail.get_by(
  180. gen_email_id=gen_email.id, website_email=website_email
  181. )
  182. if forward_email:
  183. # update the website_from if needed
  184. if forward_email.website_from != website_from_header:
  185. LOG.d("Update From header for %s", forward_email)
  186. forward_email.website_from = website_from_header
  187. db.session.commit()
  188. else:
  189. LOG.debug(
  190. "create forward email for alias %s and website email %s",
  191. gen_email,
  192. website_from_header,
  193. )
  194. # generate a reply_email, make sure it is unique
  195. # not use while loop to avoid infinite loop
  196. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  197. for _ in range(1000):
  198. if not ForwardEmail.get_by(reply_email=reply_email):
  199. # found!
  200. break
  201. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  202. forward_email = ForwardEmail.create(
  203. gen_email_id=gen_email.id,
  204. website_email=website_email,
  205. website_from=website_from_header,
  206. reply_email=reply_email,
  207. )
  208. db.session.commit()
  209. return forward_email
  210. def should_append_alias(msg, alias):
  211. """whether an alias should be appened to TO header in message"""
  212. if msg["To"] and alias in msg["To"]:
  213. return False
  214. if msg["Cc"] and alias in msg["Cc"]:
  215. return False
  216. return True
  217. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  218. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  219. # copy all headers from original message except the "Content-Type"
  220. for i in reversed(range(len(orig_msg._headers))):
  221. header_name = orig_msg._headers[i][0].lower()
  222. if header_name != "Content-Type".lower():
  223. msg[header_name] = orig_msg._headers[i][1]
  224. # Delete unnecessary headers in orig_msg except to save space
  225. delete_all_headers_except(
  226. orig_msg,
  227. [
  228. "MIME-Version",
  229. "Content-Type",
  230. "Content-Disposition",
  231. "Content-Transfer-Encoding",
  232. ],
  233. )
  234. first = MIMEApplication(
  235. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  236. )
  237. first.set_payload("Version: 1")
  238. msg.attach(first)
  239. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  240. second.add_header("Content-Disposition", "inline")
  241. # encrypt original message
  242. encrypted_data = pgp_utils.encrypt(orig_msg.as_string(), pgp_fingerprint)
  243. second.set_payload(encrypted_data)
  244. msg.attach(second)
  245. return msg
  246. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  247. """return *status_code message*"""
  248. alias = rcpt_to.lower() # alias@SL
  249. gen_email = GenEmail.get_by(email=alias)
  250. if not gen_email:
  251. LOG.d("alias %s not exist. Try to see if it can be created on the fly", alias)
  252. gen_email = try_auto_create(alias)
  253. if not gen_email:
  254. LOG.d("alias %s cannot be created on-the-fly, return 510", alias)
  255. return "510 Email not exist"
  256. mailbox = gen_email.mailbox
  257. mailbox_email = mailbox.email
  258. # create PGP email if needed
  259. if mailbox.pgp_finger_print:
  260. LOG.d("Encrypt message using mailbox %s", mailbox)
  261. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  262. forward_email = get_or_create_forward_email(msg["From"], gen_email)
  263. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  264. if gen_email.enabled:
  265. # add custom header
  266. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  267. # remove reply-to & sender header if present
  268. delete_header(msg, "Reply-To")
  269. delete_header(msg, "Sender")
  270. # change the from header so the sender comes from @SL
  271. # so it can pass DMARC check
  272. # replace the email part in from: header
  273. website_from_header = msg["From"]
  274. website_name, website_email = parseaddr(website_from_header)
  275. new_website_name = (
  276. website_name
  277. + (" - " if website_name else "")
  278. + website_email.replace("@", " at ")
  279. )
  280. from_header = formataddr((new_website_name, forward_email.reply_email))
  281. add_or_replace_header(msg, "From", from_header)
  282. LOG.d("new from header:%s", from_header)
  283. # append alias into the TO header if it's not present in To or CC
  284. if should_append_alias(msg, alias):
  285. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  286. if msg["To"]:
  287. to_header = msg["To"] + "," + alias
  288. else:
  289. to_header = alias
  290. add_or_replace_header(msg, "To", to_header)
  291. # add List-Unsubscribe header
  292. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  293. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  294. add_or_replace_header(
  295. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  296. )
  297. add_dkim_signature(msg, EMAIL_DOMAIN)
  298. LOG.d(
  299. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  300. website_email,
  301. mailbox_email,
  302. envelope.mail_options,
  303. envelope.rcpt_options,
  304. )
  305. # smtp.send_message has UnicodeEncodeErroremail issue
  306. # encode message raw directly instead
  307. msg_raw = msg.as_string().encode()
  308. smtp.sendmail(
  309. forward_email.reply_email,
  310. mailbox_email,
  311. msg_raw,
  312. envelope.mail_options,
  313. envelope.rcpt_options,
  314. )
  315. else:
  316. LOG.d("%s is disabled, do not forward", gen_email)
  317. forward_log.blocked = True
  318. db.session.commit()
  319. return "250 Message accepted for delivery"
  320. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  321. reply_email = rcpt_to.lower()
  322. # reply_email must end with EMAIL_DOMAIN
  323. if not reply_email.endswith(EMAIL_DOMAIN):
  324. LOG.warning(f"Reply email {reply_email} has wrong domain")
  325. return "550 wrong reply email"
  326. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  327. if not forward_email:
  328. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  329. return "550 wrong reply email"
  330. alias: str = forward_email.gen_email.email
  331. alias_domain = alias[alias.find("@") + 1 :]
  332. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  333. if not email_belongs_to_alias_domains(alias):
  334. if not CustomDomain.get_by(domain=alias_domain):
  335. return "550 alias unknown by SimpleLogin"
  336. gen_email = forward_email.gen_email
  337. user = gen_email.user
  338. mailbox_email = gen_email.mailbox_email()
  339. # bounce email initiated by Postfix
  340. # can happen in case emails cannot be delivered to user-email
  341. # in this case Postfix will try to send a bounce report to original sender, which is
  342. # the "reply email"
  343. if envelope.mail_from == "<>":
  344. LOG.error(
  345. "Bounce when sending to alias %s from %s, user %s",
  346. alias,
  347. forward_email.website_from,
  348. gen_email.user,
  349. )
  350. handle_bounce(
  351. alias, envelope, forward_email, gen_email, msg, smtp, user, mailbox_email
  352. )
  353. return "550 ignored"
  354. # only mailbox can send email to the reply-email
  355. if envelope.mail_from.lower() != mailbox_email.lower():
  356. LOG.warning(
  357. f"Reply email can only be used by user email. Actual mail_from: %s. msg from header: %s, User email %s. reply_email %s",
  358. envelope.mail_from,
  359. msg["From"],
  360. mailbox_email,
  361. reply_email,
  362. )
  363. user = gen_email.user
  364. send_email(
  365. mailbox_email,
  366. f"Reply from your alias {alias} only works from your mailbox",
  367. render(
  368. "transactional/reply-must-use-personal-email.txt",
  369. name=user.name,
  370. alias=alias,
  371. sender=envelope.mail_from,
  372. mailbox_email=mailbox_email,
  373. ),
  374. render(
  375. "transactional/reply-must-use-personal-email.html",
  376. name=user.name,
  377. alias=alias,
  378. sender=envelope.mail_from,
  379. mailbox_email=mailbox_email,
  380. ),
  381. )
  382. # Notify sender that they cannot send emails to this address
  383. send_email(
  384. envelope.mail_from,
  385. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  386. render(
  387. "transactional/send-from-alias-from-unknown-sender.txt",
  388. sender=envelope.mail_from,
  389. reply_email=reply_email,
  390. ),
  391. "",
  392. )
  393. return "550 ignored"
  394. delete_header(msg, "DKIM-Signature")
  395. # the email comes from alias
  396. add_or_replace_header(msg, "From", alias)
  397. # some email providers like ProtonMail adds automatically the Reply-To field
  398. # make sure to delete it
  399. delete_header(msg, "Reply-To")
  400. # remove sender header if present as this could reveal user real email
  401. delete_header(msg, "Sender")
  402. add_or_replace_header(msg, "To", forward_email.website_email)
  403. # add List-Unsubscribe header
  404. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  405. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  406. add_or_replace_header(msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
  407. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  408. delete_header(msg, "Received-SPF")
  409. LOG.d(
  410. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  411. alias,
  412. forward_email.website_email,
  413. envelope.mail_options,
  414. envelope.rcpt_options,
  415. )
  416. if alias_domain in ALIAS_DOMAINS:
  417. add_dkim_signature(msg, alias_domain)
  418. # add DKIM-Signature for custom-domain alias
  419. else:
  420. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  421. if custom_domain.dkim_verified:
  422. add_dkim_signature(msg, alias_domain)
  423. msg_raw = msg.as_string().encode()
  424. smtp.sendmail(
  425. alias,
  426. forward_email.website_email,
  427. msg_raw,
  428. envelope.mail_options,
  429. envelope.rcpt_options,
  430. )
  431. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  432. db.session.commit()
  433. return "250 Message accepted for delivery"
  434. def handle_bounce(
  435. alias, envelope, forward_email, gen_email, msg, smtp, user, mailbox_email
  436. ):
  437. fel: ForwardEmailLog = ForwardEmailLog.create(
  438. forward_id=forward_email.id, bounced=True
  439. )
  440. db.session.commit()
  441. nb_bounced = ForwardEmailLog.filter_by(
  442. forward_id=forward_email.id, bounced=True
  443. ).count()
  444. disable_alias_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  445. # Store the bounced email
  446. orig_msg = get_orig_message_from_bounce(msg)
  447. # generate a name for the email
  448. random_name = str(uuid.uuid4())
  449. full_report_path = f"refused-emails/full-{random_name}.eml"
  450. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  451. file_path = f"refused-emails/{random_name}.eml"
  452. s3.upload_email_from_bytesio(file_path, BytesIO(orig_msg.as_bytes()), random_name)
  453. refused_email = RefusedEmail.create(
  454. path=file_path, full_report_path=full_report_path, user_id=user.id
  455. )
  456. db.session.flush()
  457. fel.refused_email_id = refused_email.id
  458. db.session.commit()
  459. LOG.d("Create refused email %s", refused_email)
  460. refused_email_url = (
  461. URL + f"/dashboard/refused_email?highlight_fel_id=" + str(fel.id)
  462. )
  463. # inform user if this is the first bounced email
  464. if nb_bounced == 1:
  465. LOG.d(
  466. "Inform user %s about bounced email sent by %s to alias %s",
  467. user,
  468. forward_email.website_from,
  469. alias,
  470. )
  471. send_email(
  472. # use user mail here as only user is authenticated to see the refused email
  473. user.email,
  474. f"Email from {forward_email.website_from} to {alias} cannot be delivered to your inbox",
  475. render(
  476. "transactional/bounced-email.txt",
  477. name=user.name,
  478. alias=alias,
  479. website_from=forward_email.website_from,
  480. website_email=forward_email.website_email,
  481. disable_alias_link=disable_alias_link,
  482. refused_email_url=refused_email_url,
  483. mailbox_email=mailbox_email,
  484. ),
  485. render(
  486. "transactional/bounced-email.html",
  487. name=user.name,
  488. alias=alias,
  489. website_from=forward_email.website_from,
  490. website_email=forward_email.website_email,
  491. disable_alias_link=disable_alias_link,
  492. refused_email_url=refused_email_url,
  493. mailbox_email=mailbox_email,
  494. ),
  495. # cannot include bounce email as it can contain spammy text
  496. # bounced_email=msg,
  497. )
  498. # disable the alias the second time email is bounced
  499. elif nb_bounced >= 2:
  500. LOG.d(
  501. "Bounce happens again with alias %s from %s. Disable alias now ",
  502. alias,
  503. forward_email.website_from,
  504. )
  505. gen_email.enabled = False
  506. db.session.commit()
  507. send_email(
  508. # use user mail here as only user is authenticated to see the refused email
  509. user.email,
  510. f"Alias {alias} has been disabled due to second undelivered email from {forward_email.website_from}",
  511. render(
  512. "transactional/automatic-disable-alias.txt",
  513. name=user.name,
  514. alias=alias,
  515. website_from=forward_email.website_from,
  516. website_email=forward_email.website_email,
  517. refused_email_url=refused_email_url,
  518. mailbox_email=mailbox_email,
  519. ),
  520. render(
  521. "transactional/automatic-disable-alias.html",
  522. name=user.name,
  523. alias=alias,
  524. website_from=forward_email.website_from,
  525. website_email=forward_email.website_email,
  526. refused_email_url=refused_email_url,
  527. mailbox_email=mailbox_email,
  528. ),
  529. # cannot include bounce email as it can contain spammy text
  530. # bounced_email=msg,
  531. )
  532. class MailHandler:
  533. async def handle_DATA(self, server, session, envelope):
  534. LOG.debug(">>> New message <<<")
  535. LOG.debug("Mail from %s", envelope.mail_from)
  536. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  537. message_data = envelope.content.decode("utf8", errors="replace")
  538. if POSTFIX_SUBMISSION_TLS:
  539. smtp = SMTP(POSTFIX_SERVER, 587)
  540. smtp.starttls()
  541. else:
  542. smtp = SMTP(POSTFIX_SERVER, 25)
  543. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  544. for rcpt_to in envelope.rcpt_tos:
  545. # Reply case
  546. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  547. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  548. LOG.debug("Reply phase")
  549. app = new_app()
  550. with app.app_context():
  551. return handle_reply(envelope, smtp, msg, rcpt_to)
  552. else: # Forward case
  553. LOG.debug("Forward phase")
  554. app = new_app()
  555. with app.app_context():
  556. return handle_forward(envelope, smtp, msg, rcpt_to)
  557. if __name__ == "__main__":
  558. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  559. controller.start()
  560. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  561. while True:
  562. time.sleep(2)