email_handler.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. """
  2. Handle the email *forward* and *reply*. phase. There are 3 actors:
  3. - contact: 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 contact.
  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: @contact
  10. rcpt to: @personal_email
  11. Header:
  12. From: @contact
  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: @contact
  18. rcpt to: @contact
  19. Header:
  20. From: alias@sl.co # so for contact the email comes from alias. magic HERE
  21. To: @contact
  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. - @contact
  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. reply_email = generate_reply_email()
  190. contact = Contact.create(
  191. user_id=alias.user_id,
  192. alias_id=alias.id,
  193. website_email=website_email,
  194. website_from=website_from_header,
  195. reply_email=reply_email,
  196. )
  197. db.session.commit()
  198. return contact
  199. def generate_reply_email():
  200. # generate a reply_email, make sure it is unique
  201. # not use while loop to avoid infinite loop
  202. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  203. for _ in range(1000):
  204. if not Contact.get_by(reply_email=reply_email):
  205. # found!
  206. break
  207. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  208. return reply_email
  209. def should_append_alias(msg: Message, address: str):
  210. """whether an alias should be appened to TO header in message"""
  211. if msg["To"] and address in msg["To"]:
  212. return False
  213. if msg["Cc"] and address in msg["Cc"]:
  214. return False
  215. return True
  216. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  217. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  218. # copy all headers from original message except the "Content-Type"
  219. for i in reversed(range(len(orig_msg._headers))):
  220. header_name = orig_msg._headers[i][0].lower()
  221. if header_name != "Content-Type".lower():
  222. msg[header_name] = orig_msg._headers[i][1]
  223. # Delete unnecessary headers in orig_msg except to save space
  224. delete_all_headers_except(
  225. orig_msg,
  226. [
  227. "MIME-Version",
  228. "Content-Type",
  229. "Content-Disposition",
  230. "Content-Transfer-Encoding",
  231. ],
  232. )
  233. first = MIMEApplication(
  234. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  235. )
  236. first.set_payload("Version: 1")
  237. msg.attach(first)
  238. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  239. second.add_header("Content-Disposition", "inline")
  240. # encrypt original message
  241. encrypted_data = pgp_utils.encrypt(orig_msg.as_string(), pgp_fingerprint)
  242. second.set_payload(encrypted_data)
  243. msg.attach(second)
  244. return msg
  245. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  246. """return *status_code message*"""
  247. address = rcpt_to.lower() # alias@SL
  248. alias = Alias.get_by(email=address)
  249. if not alias:
  250. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  251. alias = try_auto_create(address)
  252. if not alias:
  253. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  254. return "550 SL Email not exist"
  255. mailbox = alias.mailbox
  256. mailbox_email = mailbox.email
  257. user = alias.user
  258. # create PGP email if needed
  259. if mailbox.pgp_finger_print and user.is_premium():
  260. LOG.d("Encrypt message using mailbox %s", mailbox)
  261. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  262. contact = get_or_create_contact(msg["From"], alias)
  263. forward_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  264. if alias.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. contact_from_header = msg["From"]
  274. contact_name, contact_email = parseaddr(contact_from_header)
  275. new_contact_name = f"{contact_email} via SimpleLogin"
  276. new_from_header = formataddr((new_contact_name, contact.reply_email)).strip()
  277. add_or_replace_header(msg, "From", new_from_header)
  278. LOG.d(
  279. "new from header:%s, contact_name %s, contact_email %s",
  280. new_from_header,
  281. contact_name,
  282. contact_email,
  283. )
  284. # append alias into the TO header if it's not present in To or CC
  285. if should_append_alias(msg, alias.email):
  286. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  287. if msg["To"]:
  288. to_header = msg["To"] + "," + alias.email
  289. else:
  290. to_header = alias.email
  291. add_or_replace_header(msg, "To", to_header.strip())
  292. # add List-Unsubscribe header
  293. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  294. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  295. add_or_replace_header(
  296. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  297. )
  298. add_dkim_signature(msg, EMAIL_DOMAIN)
  299. LOG.d(
  300. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  301. contact_email,
  302. mailbox_email,
  303. envelope.mail_options,
  304. envelope.rcpt_options,
  305. )
  306. # smtp.send_message has UnicodeEncodeErroremail issue
  307. # encode message raw directly instead
  308. msg_raw = msg.as_string().encode()
  309. smtp.sendmail(
  310. contact.reply_email,
  311. mailbox_email,
  312. msg_raw,
  313. envelope.mail_options,
  314. envelope.rcpt_options,
  315. )
  316. else:
  317. LOG.d("%s is disabled, do not forward", alias)
  318. forward_log.blocked = True
  319. db.session.commit()
  320. return "250 Message accepted for delivery"
  321. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  322. reply_email = rcpt_to.lower()
  323. # reply_email must end with EMAIL_DOMAIN
  324. if not reply_email.endswith(EMAIL_DOMAIN):
  325. LOG.warning(f"Reply email {reply_email} has wrong domain")
  326. return "550 SL wrong reply email"
  327. contact = Contact.get_by(reply_email=reply_email)
  328. if not contact:
  329. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  330. return "550 SL wrong reply email"
  331. address: str = contact.alias.email
  332. alias_domain = address[address.find("@") + 1 :]
  333. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  334. if not email_belongs_to_alias_domains(address):
  335. if not CustomDomain.get_by(domain=alias_domain):
  336. return "550 SL alias unknown by SimpleLogin"
  337. alias = contact.alias
  338. user = alias.user
  339. mailbox_email = alias.mailbox_email()
  340. # bounce email initiated by Postfix
  341. # can happen in case emails cannot be delivered to user-email
  342. # in this case Postfix will try to send a bounce report to original sender, which is
  343. # the "reply email"
  344. if envelope.mail_from == "<>":
  345. LOG.error(
  346. "Bounce when sending to alias %s from %s, user %s",
  347. address,
  348. contact.website_from,
  349. alias.user,
  350. )
  351. handle_bounce(contact, alias, msg, user, mailbox_email)
  352. return "550 SL ignored"
  353. # only mailbox can send email to the reply-email
  354. if envelope.mail_from.lower() != mailbox_email.lower():
  355. LOG.warning(
  356. f"Reply email can only be used by mailbox. "
  357. f"Actual mail_from: %s. msg from header: %s, Mailbox %s. reply_email %s",
  358. envelope.mail_from,
  359. msg["From"],
  360. mailbox_email,
  361. reply_email,
  362. )
  363. user = alias.user
  364. send_email(
  365. mailbox_email,
  366. f"Reply from your alias {address} only works from your mailbox",
  367. render(
  368. "transactional/reply-must-use-personal-email.txt",
  369. name=user.name,
  370. alias=address,
  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=address,
  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 SL ignored"
  394. delete_header(msg, "DKIM-Signature")
  395. # the email comes from alias
  396. add_or_replace_header(msg, "From", address)
  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", contact.website_email)
  403. # add List-Unsubscribe header
  404. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{contact.alias_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. address,
  412. contact.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. address,
  426. contact.website_email,
  427. msg_raw,
  428. envelope.mail_options,
  429. envelope.rcpt_options,
  430. )
  431. EmailLog.create(contact_id=contact.id, is_reply=True, user_id=contact.user_id)
  432. db.session.commit()
  433. return "250 Message accepted for delivery"
  434. def handle_bounce(
  435. contact: Contact, alias: Alias, msg: Message, user: User, mailbox_email: str
  436. ):
  437. address = alias.email
  438. fel: EmailLog = EmailLog.create(
  439. contact_id=contact.id, bounced=True, user_id=contact.user_id
  440. )
  441. db.session.commit()
  442. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  443. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  444. # Store the bounced email
  445. orig_msg = get_orig_message_from_bounce(msg)
  446. # generate a name for the email
  447. random_name = str(uuid.uuid4())
  448. full_report_path = f"refused-emails/full-{random_name}.eml"
  449. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  450. file_path = None
  451. if orig_msg:
  452. file_path = f"refused-emails/{random_name}.eml"
  453. s3.upload_email_from_bytesio(
  454. file_path, BytesIO(orig_msg.as_bytes()), random_name
  455. )
  456. refused_email = RefusedEmail.create(
  457. path=file_path, full_report_path=full_report_path, user_id=user.id
  458. )
  459. db.session.flush()
  460. fel.refused_email_id = refused_email.id
  461. db.session.commit()
  462. LOG.d("Create refused email %s", refused_email)
  463. refused_email_url = (
  464. URL + f"/dashboard/refused_email?highlight_fel_id=" + str(fel.id)
  465. )
  466. # inform user if this is the first bounced email
  467. if nb_bounced == 1:
  468. LOG.d(
  469. "Inform user %s about bounced email sent by %s to alias %s",
  470. user,
  471. contact.website_from,
  472. address,
  473. )
  474. send_email(
  475. # use user mail here as only user is authenticated to see the refused email
  476. user.email,
  477. f"Email from {contact.website_from} to {address} cannot be delivered to your inbox",
  478. render(
  479. "transactional/bounced-email.txt",
  480. name=user.name,
  481. alias=alias,
  482. website_from=contact.website_from,
  483. website_email=contact.website_email,
  484. disable_alias_link=disable_alias_link,
  485. refused_email_url=refused_email_url,
  486. mailbox_email=mailbox_email,
  487. ),
  488. render(
  489. "transactional/bounced-email.html",
  490. name=user.name,
  491. alias=alias,
  492. website_from=contact.website_from,
  493. website_email=contact.website_email,
  494. disable_alias_link=disable_alias_link,
  495. refused_email_url=refused_email_url,
  496. mailbox_email=mailbox_email,
  497. ),
  498. # cannot include bounce email as it can contain spammy text
  499. # bounced_email=msg,
  500. )
  501. # disable the alias the second time email is bounced
  502. elif nb_bounced >= 2:
  503. LOG.d(
  504. "Bounce happens again with alias %s from %s. Disable alias now ",
  505. address,
  506. contact.website_from,
  507. )
  508. alias.enabled = False
  509. db.session.commit()
  510. send_email(
  511. # use user mail here as only user is authenticated to see the refused email
  512. user.email,
  513. f"Alias {address} has been disabled due to second undelivered email from {contact.website_from}",
  514. render(
  515. "transactional/automatic-disable-alias.txt",
  516. name=user.name,
  517. alias=alias,
  518. website_from=contact.website_from,
  519. website_email=contact.website_email,
  520. refused_email_url=refused_email_url,
  521. mailbox_email=mailbox_email,
  522. ),
  523. render(
  524. "transactional/automatic-disable-alias.html",
  525. name=user.name,
  526. alias=alias,
  527. website_from=contact.website_from,
  528. website_email=contact.website_email,
  529. refused_email_url=refused_email_url,
  530. mailbox_email=mailbox_email,
  531. ),
  532. # cannot include bounce email as it can contain spammy text
  533. # bounced_email=msg,
  534. )
  535. class MailHandler:
  536. async def handle_DATA(self, server, session, envelope):
  537. LOG.debug(">>> New message <<<")
  538. LOG.debug("Mail from %s", envelope.mail_from)
  539. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  540. message_data = envelope.content.decode("utf8", errors="replace")
  541. if POSTFIX_SUBMISSION_TLS:
  542. smtp = SMTP(POSTFIX_SERVER, 587)
  543. smtp.starttls()
  544. else:
  545. smtp = SMTP(POSTFIX_SERVER, 25)
  546. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  547. for rcpt_to in envelope.rcpt_tos:
  548. # Reply case
  549. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  550. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  551. LOG.debug("Reply phase")
  552. app = new_app()
  553. with app.app_context():
  554. return handle_reply(envelope, smtp, msg, rcpt_to)
  555. else: # Forward case
  556. LOG.debug("Forward phase")
  557. app = new_app()
  558. with app.app_context():
  559. return handle_forward(envelope, smtp, msg, rcpt_to)
  560. if __name__ == "__main__":
  561. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  562. controller.start()
  563. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  564. while True:
  565. time.sleep(2)