email_handler.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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: Message, address: str):
  206. """whether an alias should be appened to TO header in message"""
  207. if msg["To"] and address in msg["To"]:
  208. return False
  209. if msg["Cc"] and address 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. address = rcpt_to.lower() # alias@SL
  244. alias = Alias.get_by(email=address)
  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(address)
  248. if not alias:
  249. LOG.d("alias %s cannot be created on-the-fly, return 510", address)
  250. return "510 Email not exist"
  251. mailbox = alias.mailbox
  252. mailbox_email = mailbox.email
  253. user = alias.user
  254. # create PGP email if needed
  255. if mailbox.pgp_finger_print and user.is_premium():
  256. LOG.d("Encrypt message using mailbox %s", mailbox)
  257. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  258. contact = get_or_create_contact(msg["From"], alias)
  259. forward_log = EmailLog.create(contact_id=contact.id)
  260. if alias.enabled:
  261. # add custom header
  262. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  263. # remove reply-to & sender header if present
  264. delete_header(msg, "Reply-To")
  265. delete_header(msg, "Sender")
  266. # change the from header so the sender comes from @SL
  267. # so it can pass DMARC check
  268. # replace the email part in from: header
  269. website_from_header = msg["From"]
  270. website_name, website_email = parseaddr(website_from_header)
  271. new_website_name = (
  272. website_name
  273. + (" - " if website_name else "")
  274. + website_email.replace("@", " at ")
  275. )
  276. from_header = formataddr((new_website_name, contact.reply_email))
  277. add_or_replace_header(msg, "From", from_header)
  278. LOG.d("new from header:%s", from_header)
  279. # append alias into the TO header if it's not present in To or CC
  280. if should_append_alias(msg, alias.email):
  281. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  282. if msg["To"]:
  283. to_header = msg["To"] + "," + alias.email
  284. else:
  285. to_header = alias.email
  286. add_or_replace_header(msg, "To", to_header)
  287. # add List-Unsubscribe header
  288. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.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. add_dkim_signature(msg, EMAIL_DOMAIN)
  294. LOG.d(
  295. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  296. website_email,
  297. mailbox_email,
  298. envelope.mail_options,
  299. envelope.rcpt_options,
  300. )
  301. # smtp.send_message has UnicodeEncodeErroremail issue
  302. # encode message raw directly instead
  303. msg_raw = msg.as_string().encode()
  304. smtp.sendmail(
  305. contact.reply_email,
  306. mailbox_email,
  307. msg_raw,
  308. envelope.mail_options,
  309. envelope.rcpt_options,
  310. )
  311. else:
  312. LOG.d("%s is disabled, do not forward", alias)
  313. forward_log.blocked = True
  314. db.session.commit()
  315. return "250 Message accepted for delivery"
  316. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  317. reply_email = rcpt_to.lower()
  318. # reply_email must end with EMAIL_DOMAIN
  319. if not reply_email.endswith(EMAIL_DOMAIN):
  320. LOG.warning(f"Reply email {reply_email} has wrong domain")
  321. return "550 wrong reply email"
  322. contact = Contact.get_by(reply_email=reply_email)
  323. if not contact:
  324. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  325. return "550 wrong reply email"
  326. address: str = contact.alias.email
  327. alias_domain = address[address.find("@") + 1 :]
  328. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  329. if not email_belongs_to_alias_domains(address):
  330. if not CustomDomain.get_by(domain=alias_domain):
  331. return "550 alias unknown by SimpleLogin"
  332. alias = contact.alias
  333. user = alias.user
  334. mailbox_email = alias.mailbox_email()
  335. # bounce email initiated by Postfix
  336. # can happen in case emails cannot be delivered to user-email
  337. # in this case Postfix will try to send a bounce report to original sender, which is
  338. # the "reply email"
  339. if envelope.mail_from == "<>":
  340. LOG.error(
  341. "Bounce when sending to alias %s from %s, user %s",
  342. address,
  343. contact.website_from,
  344. alias.user,
  345. )
  346. handle_bounce(contact, alias, msg, user, mailbox_email)
  347. return "550 ignored"
  348. # only mailbox can send email to the reply-email
  349. if envelope.mail_from.lower() != mailbox_email.lower():
  350. LOG.warning(
  351. f"Reply email can only be used by mailbox. "
  352. f"Actual mail_from: %s. msg from header: %s, Mailbox %s. reply_email %s",
  353. envelope.mail_from,
  354. msg["From"],
  355. mailbox_email,
  356. reply_email,
  357. )
  358. user = alias.user
  359. send_email(
  360. mailbox_email,
  361. f"Reply from your alias {address} only works from your mailbox",
  362. render(
  363. "transactional/reply-must-use-personal-email.txt",
  364. name=user.name,
  365. alias=address,
  366. sender=envelope.mail_from,
  367. mailbox_email=mailbox_email,
  368. ),
  369. render(
  370. "transactional/reply-must-use-personal-email.html",
  371. name=user.name,
  372. alias=address,
  373. sender=envelope.mail_from,
  374. mailbox_email=mailbox_email,
  375. ),
  376. )
  377. # Notify sender that they cannot send emails to this address
  378. send_email(
  379. envelope.mail_from,
  380. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  381. render(
  382. "transactional/send-from-alias-from-unknown-sender.txt",
  383. sender=envelope.mail_from,
  384. reply_email=reply_email,
  385. ),
  386. "",
  387. )
  388. return "550 ignored"
  389. delete_header(msg, "DKIM-Signature")
  390. # the email comes from alias
  391. add_or_replace_header(msg, "From", address)
  392. # some email providers like ProtonMail adds automatically the Reply-To field
  393. # make sure to delete it
  394. delete_header(msg, "Reply-To")
  395. # remove sender header if present as this could reveal user real email
  396. delete_header(msg, "Sender")
  397. add_or_replace_header(msg, "To", contact.website_email)
  398. # add List-Unsubscribe header
  399. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{contact.alias_id}"
  400. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  401. add_or_replace_header(msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
  402. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  403. delete_header(msg, "Received-SPF")
  404. LOG.d(
  405. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  406. address,
  407. contact.website_email,
  408. envelope.mail_options,
  409. envelope.rcpt_options,
  410. )
  411. if alias_domain in ALIAS_DOMAINS:
  412. add_dkim_signature(msg, alias_domain)
  413. # add DKIM-Signature for custom-domain alias
  414. else:
  415. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  416. if custom_domain.dkim_verified:
  417. add_dkim_signature(msg, alias_domain)
  418. msg_raw = msg.as_string().encode()
  419. smtp.sendmail(
  420. address,
  421. contact.website_email,
  422. msg_raw,
  423. envelope.mail_options,
  424. envelope.rcpt_options,
  425. )
  426. EmailLog.create(contact_id=contact.id, is_reply=True)
  427. db.session.commit()
  428. return "250 Message accepted for delivery"
  429. def handle_bounce(
  430. contact: Contact, alias: Alias, msg: Message, user: User, mailbox_email: str
  431. ):
  432. address = alias.email
  433. fel: EmailLog = EmailLog.create(contact_id=contact.id, bounced=True)
  434. db.session.commit()
  435. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  436. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  437. # Store the bounced email
  438. orig_msg = get_orig_message_from_bounce(msg)
  439. # generate a name for the email
  440. random_name = str(uuid.uuid4())
  441. full_report_path = f"refused-emails/full-{random_name}.eml"
  442. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  443. file_path = f"refused-emails/{random_name}.eml"
  444. s3.upload_email_from_bytesio(file_path, BytesIO(orig_msg.as_bytes()), random_name)
  445. refused_email = RefusedEmail.create(
  446. path=file_path, full_report_path=full_report_path, user_id=user.id
  447. )
  448. db.session.flush()
  449. fel.refused_email_id = refused_email.id
  450. db.session.commit()
  451. LOG.d("Create refused email %s", refused_email)
  452. refused_email_url = (
  453. URL + f"/dashboard/refused_email?highlight_fel_id=" + str(fel.id)
  454. )
  455. # inform user if this is the first bounced email
  456. if nb_bounced == 1:
  457. LOG.d(
  458. "Inform user %s about bounced email sent by %s to alias %s",
  459. user,
  460. contact.website_from,
  461. address,
  462. )
  463. send_email(
  464. # use user mail here as only user is authenticated to see the refused email
  465. user.email,
  466. f"Email from {contact.website_from} to {address} cannot be delivered to your inbox",
  467. render(
  468. "transactional/bounced-email.txt",
  469. name=user.name,
  470. alias=alias,
  471. website_from=contact.website_from,
  472. website_email=contact.website_email,
  473. disable_alias_link=disable_alias_link,
  474. refused_email_url=refused_email_url,
  475. mailbox_email=mailbox_email,
  476. ),
  477. render(
  478. "transactional/bounced-email.html",
  479. name=user.name,
  480. alias=alias,
  481. website_from=contact.website_from,
  482. website_email=contact.website_email,
  483. disable_alias_link=disable_alias_link,
  484. refused_email_url=refused_email_url,
  485. mailbox_email=mailbox_email,
  486. ),
  487. # cannot include bounce email as it can contain spammy text
  488. # bounced_email=msg,
  489. )
  490. # disable the alias the second time email is bounced
  491. elif nb_bounced >= 2:
  492. LOG.d(
  493. "Bounce happens again with alias %s from %s. Disable alias now ",
  494. address,
  495. contact.website_from,
  496. )
  497. alias.enabled = False
  498. db.session.commit()
  499. send_email(
  500. # use user mail here as only user is authenticated to see the refused email
  501. user.email,
  502. f"Alias {address} has been disabled due to second undelivered email from {contact.website_from}",
  503. render(
  504. "transactional/automatic-disable-alias.txt",
  505. name=user.name,
  506. alias=alias,
  507. website_from=contact.website_from,
  508. website_email=contact.website_email,
  509. refused_email_url=refused_email_url,
  510. mailbox_email=mailbox_email,
  511. ),
  512. render(
  513. "transactional/automatic-disable-alias.html",
  514. name=user.name,
  515. alias=alias,
  516. website_from=contact.website_from,
  517. website_email=contact.website_email,
  518. refused_email_url=refused_email_url,
  519. mailbox_email=mailbox_email,
  520. ),
  521. # cannot include bounce email as it can contain spammy text
  522. # bounced_email=msg,
  523. )
  524. class MailHandler:
  525. async def handle_DATA(self, server, session, envelope):
  526. LOG.debug(">>> New message <<<")
  527. LOG.debug("Mail from %s", envelope.mail_from)
  528. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  529. message_data = envelope.content.decode("utf8", errors="replace")
  530. if POSTFIX_SUBMISSION_TLS:
  531. smtp = SMTP(POSTFIX_SERVER, 587)
  532. smtp.starttls()
  533. else:
  534. smtp = SMTP(POSTFIX_SERVER, 25)
  535. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  536. for rcpt_to in envelope.rcpt_tos:
  537. # Reply case
  538. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  539. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  540. LOG.debug("Reply phase")
  541. app = new_app()
  542. with app.app_context():
  543. return handle_reply(envelope, smtp, msg, rcpt_to)
  544. else: # Forward case
  545. LOG.debug("Forward phase")
  546. app = new_app()
  547. with app.app_context():
  548. return handle_forward(envelope, smtp, msg, rcpt_to)
  549. if __name__ == "__main__":
  550. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  551. controller.start()
  552. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  553. while True:
  554. time.sleep(2)