email_handler.py 21 KB

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