email_handler.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 email
  28. import re
  29. import arrow
  30. import spf
  31. import time
  32. import uuid
  33. from aiosmtpd.controller import Controller
  34. from aiosmtpd.smtp import Envelope
  35. from email import encoders
  36. from email.message import Message
  37. from email.mime.application import MIMEApplication
  38. from email.mime.multipart import MIMEMultipart
  39. from email.utils import parseaddr, formataddr
  40. from io import BytesIO
  41. from smtplib import SMTP
  42. from app import pgp_utils, s3
  43. from app.alias_utils import try_auto_create
  44. from app.config import (
  45. EMAIL_DOMAIN,
  46. POSTFIX_SERVER,
  47. URL,
  48. ALIAS_DOMAINS,
  49. POSTFIX_SUBMISSION_TLS,
  50. UNSUBSCRIBER,
  51. LOAD_PGP_EMAIL_HANDLER,
  52. ENFORCE_SPF,
  53. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  54. ALERT_BOUNCE_EMAIL,
  55. ALERT_SPAM_EMAIL,
  56. ALERT_SPF,
  57. )
  58. from app.email_utils import (
  59. send_email,
  60. add_dkim_signature,
  61. add_or_replace_header,
  62. delete_header,
  63. email_belongs_to_alias_domains,
  64. render,
  65. get_orig_message_from_bounce,
  66. delete_all_headers_except,
  67. get_addrs_from_header,
  68. get_spam_info,
  69. get_orig_message_from_spamassassin_report,
  70. parseaddr_unicode,
  71. send_email_with_rate_control,
  72. )
  73. from app.extensions import db
  74. from app.greylisting import greylisting_needed
  75. from app.log import LOG
  76. from app.models import (
  77. Alias,
  78. Contact,
  79. EmailLog,
  80. CustomDomain,
  81. User,
  82. RefusedEmail,
  83. Mailbox,
  84. )
  85. from app.utils import random_string
  86. from init_app import load_pgp_public_keys
  87. from server import create_app
  88. # used when an alias receives email from its own mailbox
  89. # can happen when user "Reply All" on some email clients
  90. _SELF_FORWARDING_STATUS = "550 SL self-forward"
  91. _IP_HEADER = "X-SimpleLogin-Client-IP"
  92. # fix the database connection leak issue
  93. # use this method instead of create_app
  94. def new_app():
  95. app = create_app()
  96. @app.teardown_appcontext
  97. def shutdown_session(response_or_exc):
  98. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  99. db.session.remove()
  100. # dispose the engine too
  101. db.engine.dispose()
  102. return app
  103. def get_or_create_contact(
  104. contact_from_header: str, mail_from: str, alias: Alias
  105. ) -> Contact:
  106. """
  107. contact_from_header is the RFC 2047 format FROM header
  108. """
  109. # contact_from_header can be None, use mail_from in this case instead
  110. contact_from_header = contact_from_header or mail_from
  111. # force convert header to string, sometimes contact_from_header is Header object
  112. contact_from_header = str(contact_from_header)
  113. contact_name, contact_email = parseaddr_unicode(contact_from_header)
  114. if not contact_email:
  115. # From header is wrongly formatted, try with mail_from
  116. LOG.warning("From header is empty, parse mail_from %s %s", mail_from, alias)
  117. contact_name, contact_email = parseaddr_unicode(mail_from)
  118. if not contact_email:
  119. LOG.error(
  120. "Cannot parse contact from from_header:%s, mail_from:%s",
  121. contact_from_header,
  122. mail_from,
  123. )
  124. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  125. if contact:
  126. if contact.name != contact_name:
  127. LOG.d(
  128. "Update contact %s name %s to %s", contact, contact.name, contact_name,
  129. )
  130. contact.name = contact_name
  131. db.session.commit()
  132. else:
  133. LOG.debug(
  134. "create contact for alias %s and contact %s", alias, contact_from_header,
  135. )
  136. reply_email = generate_reply_email()
  137. contact = Contact.create(
  138. user_id=alias.user_id,
  139. alias_id=alias.id,
  140. website_email=contact_email,
  141. name=contact_name,
  142. reply_email=reply_email,
  143. )
  144. db.session.commit()
  145. return contact
  146. def replace_header_when_forward(msg: Message, alias: Alias, header: str):
  147. """
  148. Replace CC or To header by Reply emails in forward phase
  149. """
  150. addrs = get_addrs_from_header(msg, header)
  151. # Nothing to do
  152. if not addrs:
  153. return
  154. new_addrs: [str] = []
  155. need_replace = False
  156. for addr in addrs:
  157. contact_name, contact_email = parseaddr_unicode(addr)
  158. # no transformation when alias is already in the header
  159. if contact_email == alias.email:
  160. new_addrs.append(addr)
  161. continue
  162. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  163. if contact:
  164. # update the contact name if needed
  165. if contact.name != contact_name:
  166. LOG.d(
  167. "Update contact %s name %s to %s",
  168. contact,
  169. contact.name,
  170. contact_name,
  171. )
  172. contact.name = contact_name
  173. db.session.commit()
  174. else:
  175. LOG.debug(
  176. "create contact for alias %s and email %s, header %s",
  177. alias,
  178. contact_email,
  179. header,
  180. )
  181. reply_email = generate_reply_email()
  182. contact = Contact.create(
  183. user_id=alias.user_id,
  184. alias_id=alias.id,
  185. website_email=contact_email,
  186. name=contact_name,
  187. reply_email=reply_email,
  188. is_cc=header.lower() == "cc",
  189. )
  190. db.session.commit()
  191. new_addrs.append(contact.new_addr())
  192. need_replace = True
  193. if need_replace:
  194. new_header = ",".join(new_addrs)
  195. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  196. add_or_replace_header(msg, header, new_header)
  197. else:
  198. LOG.d("No need to replace %s header", header)
  199. def replace_header_when_reply(msg: Message, alias: Alias, header: str):
  200. """
  201. Replace CC or To Reply emails by original emails
  202. """
  203. addrs = get_addrs_from_header(msg, header)
  204. # Nothing to do
  205. if not addrs:
  206. return
  207. new_addrs: [str] = []
  208. for addr in addrs:
  209. name, reply_email = parseaddr(addr)
  210. # no transformation when alias is already in the header
  211. if reply_email == alias.email:
  212. continue
  213. contact = Contact.get_by(reply_email=reply_email)
  214. if not contact:
  215. LOG.warning(
  216. "%s email in reply phase %s must be reply emails", header, reply_email
  217. )
  218. # still keep this email in header
  219. new_addrs.append(addr)
  220. else:
  221. new_addrs.append(formataddr((contact.name, contact.website_email)))
  222. new_header = ",".join(new_addrs)
  223. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  224. add_or_replace_header(msg, header, new_header)
  225. def generate_reply_email():
  226. # generate a reply_email, make sure it is unique
  227. # not use while loop to avoid infinite loop
  228. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  229. for _ in range(1000):
  230. if not Contact.get_by(reply_email=reply_email):
  231. # found!
  232. break
  233. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  234. return reply_email
  235. def should_append_alias(msg: Message, address: str):
  236. """whether an alias should be appended to TO header in message"""
  237. if msg["To"] and address in msg["To"]:
  238. return False
  239. if msg["Cc"] and address in msg["Cc"]:
  240. return False
  241. return True
  242. _MIME_HEADERS = [
  243. "MIME-Version",
  244. "Content-Type",
  245. "Content-Disposition",
  246. "Content-Transfer-Encoding",
  247. ]
  248. _MIME_HEADERS = [h.lower() for h in _MIME_HEADERS]
  249. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  250. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  251. # copy all headers from original message except all standard MIME headers
  252. for i in reversed(range(len(orig_msg._headers))):
  253. header_name = orig_msg._headers[i][0].lower()
  254. if header_name.lower() not in _MIME_HEADERS:
  255. msg[header_name] = orig_msg._headers[i][1]
  256. # Delete unnecessary headers in orig_msg except to save space
  257. delete_all_headers_except(
  258. orig_msg, _MIME_HEADERS,
  259. )
  260. first = MIMEApplication(
  261. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  262. )
  263. first.set_payload("Version: 1")
  264. msg.attach(first)
  265. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  266. second.add_header("Content-Disposition", "inline")
  267. # encrypt original message
  268. encrypted_data = pgp_utils.encrypt_file(
  269. BytesIO(orig_msg.as_bytes()), pgp_fingerprint
  270. )
  271. second.set_payload(encrypted_data)
  272. msg.attach(second)
  273. return msg
  274. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  275. """return whether an email has been delivered and
  276. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  277. """
  278. address = rcpt_to.lower() # alias@SL
  279. alias = Alias.get_by(email=address)
  280. if not alias:
  281. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  282. alias = try_auto_create(address)
  283. if not alias:
  284. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  285. return False, "550 SL E3"
  286. mailbox = alias.mailbox
  287. mailbox_email = mailbox.email
  288. user = alias.user
  289. # Sometimes when user clicks on "reply all"
  290. # an email is sent to the same alias that the previous message is destined to
  291. if envelope.mail_from == mailbox_email:
  292. # nothing to do
  293. LOG.d("Forward from %s to %s, nothing to do", envelope.mail_from, mailbox_email)
  294. return False, _SELF_FORWARDING_STATUS
  295. contact = get_or_create_contact(msg["From"], envelope.mail_from, alias)
  296. email_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  297. if not alias.enabled:
  298. LOG.d("%s is disabled, do not forward", alias)
  299. email_log.blocked = True
  300. db.session.commit()
  301. return True, "250 Message accepted for delivery"
  302. is_spam, spam_status = get_spam_info(msg)
  303. if is_spam:
  304. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  305. email_log.is_spam = True
  306. email_log.spam_status = spam_status
  307. handle_spam(contact, alias, msg, user, mailbox_email, email_log)
  308. return False, "550 SL E1"
  309. # create PGP email if needed
  310. if mailbox.pgp_finger_print and user.is_premium():
  311. LOG.d("Encrypt message using mailbox %s", mailbox)
  312. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  313. # add custom header
  314. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  315. # remove reply-to & sender header if present
  316. delete_header(msg, "Reply-To")
  317. delete_header(msg, "Sender")
  318. delete_header(msg, _IP_HEADER)
  319. # change the from header so the sender comes from @SL
  320. # so it can pass DMARC check
  321. # replace the email part in from: header
  322. contact_from_header = msg["From"]
  323. new_from_header = contact.new_addr()
  324. add_or_replace_header(msg, "From", new_from_header)
  325. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  326. # replace CC & To emails by reply-email for all emails that are not alias
  327. replace_header_when_forward(msg, alias, "Cc")
  328. replace_header_when_forward(msg, alias, "To")
  329. # append alias into the TO header if it's not present in To or CC
  330. if should_append_alias(msg, alias.email):
  331. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  332. if msg["To"]:
  333. to_header = msg["To"] + "," + alias.email
  334. else:
  335. to_header = alias.email
  336. add_or_replace_header(msg, "To", to_header.strip())
  337. # add List-Unsubscribe header
  338. if UNSUBSCRIBER:
  339. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  340. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  341. else:
  342. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  343. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  344. add_or_replace_header(
  345. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  346. )
  347. add_dkim_signature(msg, EMAIL_DOMAIN)
  348. LOG.d(
  349. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  350. contact.website_email,
  351. mailbox_email,
  352. envelope.mail_options,
  353. envelope.rcpt_options,
  354. )
  355. # smtp.send_message has UnicodeEncodeErroremail issue
  356. # encode message raw directly instead
  357. smtp.sendmail(
  358. contact.reply_email,
  359. mailbox_email,
  360. msg.as_bytes(),
  361. envelope.mail_options,
  362. envelope.rcpt_options,
  363. )
  364. db.session.commit()
  365. return True, "250 Message accepted for delivery"
  366. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  367. """
  368. return whether an email has been delivered and
  369. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  370. """
  371. reply_email = rcpt_to.lower()
  372. # reply_email must end with EMAIL_DOMAIN
  373. if not reply_email.endswith(EMAIL_DOMAIN):
  374. LOG.warning(f"Reply email {reply_email} has wrong domain")
  375. return False, "550 SL E2"
  376. contact = Contact.get_by(reply_email=reply_email)
  377. if not contact:
  378. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  379. return False, "550 SL E4"
  380. alias = contact.alias
  381. address: str = contact.alias.email
  382. alias_domain = address[address.find("@") + 1 :]
  383. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  384. if not email_belongs_to_alias_domains(alias.email):
  385. if not CustomDomain.get_by(domain=alias_domain):
  386. return False, "550 SL E5"
  387. user = alias.user
  388. mailbox_email = alias.mailbox_email()
  389. # bounce email initiated by Postfix
  390. # can happen in case emails cannot be delivered to user-email
  391. # in this case Postfix will try to send a bounce report to original sender, which is
  392. # the "reply email"
  393. if envelope.mail_from == "<>":
  394. LOG.warning(
  395. "Bounce when sending to alias %s from %s, user %s",
  396. alias,
  397. contact.website_email,
  398. alias.user,
  399. )
  400. handle_bounce(contact, alias, msg, user, mailbox_email)
  401. return False, "550 SL E6"
  402. mailbox: Mailbox = Mailbox.get_by(email=mailbox_email)
  403. if ENFORCE_SPF and mailbox.force_spf:
  404. ip = msg[_IP_HEADER]
  405. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  406. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  407. return True, "250 SL E11"
  408. delete_header(msg, _IP_HEADER)
  409. # only mailbox can send email to the reply-email
  410. if envelope.mail_from.lower() != mailbox_email.lower():
  411. handle_unknown_mailbox(envelope, msg, mailbox, reply_email, user, alias)
  412. return False, "550 SL E7"
  413. delete_header(msg, "DKIM-Signature")
  414. delete_header(msg, "Received")
  415. # make the email comes from alias
  416. from_header = alias.email
  417. # add alias name from alias
  418. if alias.name:
  419. LOG.d("Put alias name in from header")
  420. from_header = formataddr((alias.name, alias.email))
  421. elif alias.custom_domain:
  422. LOG.d("Put domain default alias name in from header")
  423. # add alias name from domain
  424. if alias.custom_domain.name:
  425. from_header = formataddr((alias.custom_domain.name, alias.email))
  426. add_or_replace_header(msg, "From", from_header)
  427. # some email providers like ProtonMail adds automatically the Reply-To field
  428. # make sure to delete it
  429. delete_header(msg, "Reply-To")
  430. # remove sender header if present as this could reveal user real email
  431. delete_header(msg, "Sender")
  432. delete_header(msg, "X-Sender")
  433. replace_header_when_reply(msg, alias, "To")
  434. replace_header_when_reply(msg, alias, "Cc")
  435. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  436. delete_header(msg, "Received-SPF")
  437. LOG.d(
  438. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  439. alias.email,
  440. contact.website_email,
  441. envelope.mail_options,
  442. envelope.rcpt_options,
  443. )
  444. if alias_domain in ALIAS_DOMAINS:
  445. add_dkim_signature(msg, alias_domain)
  446. # add DKIM-Signature for custom-domain alias
  447. else:
  448. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  449. if custom_domain.dkim_verified:
  450. add_dkim_signature(msg, alias_domain)
  451. smtp.sendmail(
  452. alias.email,
  453. contact.website_email,
  454. msg.as_bytes(),
  455. envelope.mail_options,
  456. envelope.rcpt_options,
  457. )
  458. EmailLog.create(contact_id=contact.id, is_reply=True, user_id=contact.user_id)
  459. db.session.commit()
  460. return True, "250 Message accepted for delivery"
  461. def spf_pass(
  462. ip: str,
  463. envelope,
  464. mailbox: Mailbox,
  465. user: User,
  466. alias: Alias,
  467. contact_email: str,
  468. msg: Message,
  469. ) -> bool:
  470. if ip:
  471. LOG.d("Enforce SPF")
  472. try:
  473. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  474. except Exception:
  475. LOG.error("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  476. else:
  477. # TODO: Handle temperr case (e.g. dns timeout)
  478. # only an absolute pass, or no SPF policy at all is 'valid'
  479. if r[0] not in ["pass", "none"]:
  480. LOG.error(
  481. "SPF fail for mailbox %s, reason %s, failed IP %s",
  482. mailbox.email,
  483. r[0],
  484. ip,
  485. )
  486. send_email_with_rate_control(
  487. user,
  488. ALERT_SPF,
  489. mailbox.email,
  490. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  491. render(
  492. "transactional/spf-fail.txt",
  493. name=user.name,
  494. alias=alias.email,
  495. ip=ip,
  496. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  497. to_email=contact_email,
  498. subject=msg["Subject"],
  499. time=arrow.now(),
  500. ),
  501. render(
  502. "transactional/spf-fail.html",
  503. name=user.name,
  504. alias=alias.email,
  505. ip=ip,
  506. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  507. to_email=contact_email,
  508. subject=msg["Subject"],
  509. time=arrow.now(),
  510. ),
  511. )
  512. return False
  513. else:
  514. LOG.warning(
  515. "Could not find %s header %s -> %s",
  516. _IP_HEADER,
  517. mailbox.email,
  518. contact_email,
  519. )
  520. return True
  521. def handle_unknown_mailbox(
  522. envelope, msg, mailbox: Mailbox, reply_email: str, user: User, alias: Alias
  523. ):
  524. LOG.warning(
  525. f"Reply email can only be used by mailbox. "
  526. f"Actual mail_from: %s. msg from header: %s, Mailbox %s. reply_email %s",
  527. envelope.mail_from,
  528. msg["From"],
  529. mailbox.email,
  530. reply_email,
  531. )
  532. send_email_with_rate_control(
  533. user,
  534. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  535. mailbox.email,
  536. f"Reply from your alias {alias.email} only works from your mailbox",
  537. render(
  538. "transactional/reply-must-use-personal-email.txt",
  539. name=user.name,
  540. alias=alias.email,
  541. sender=envelope.mail_from,
  542. mailbox_email=mailbox.email,
  543. ),
  544. render(
  545. "transactional/reply-must-use-personal-email.html",
  546. name=user.name,
  547. alias=alias.email,
  548. sender=envelope.mail_from,
  549. mailbox_email=mailbox.email,
  550. ),
  551. )
  552. # Notify sender that they cannot send emails to this address
  553. send_email_with_rate_control(
  554. user,
  555. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  556. envelope.mail_from,
  557. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  558. render(
  559. "transactional/send-from-alias-from-unknown-sender.txt",
  560. sender=envelope.mail_from,
  561. reply_email=reply_email,
  562. ),
  563. render(
  564. "transactional/send-from-alias-from-unknown-sender.html",
  565. sender=envelope.mail_from,
  566. reply_email=reply_email,
  567. ),
  568. )
  569. def handle_bounce(
  570. contact: Contact, alias: Alias, msg: Message, user: User, mailbox_email: str
  571. ):
  572. address = alias.email
  573. email_log: EmailLog = EmailLog.create(
  574. contact_id=contact.id, bounced=True, user_id=contact.user_id
  575. )
  576. db.session.commit()
  577. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  578. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  579. # Store the bounced email
  580. orig_msg = get_orig_message_from_bounce(msg)
  581. # generate a name for the email
  582. random_name = str(uuid.uuid4())
  583. full_report_path = f"refused-emails/full-{random_name}.eml"
  584. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  585. file_path = None
  586. if orig_msg:
  587. file_path = f"refused-emails/{random_name}.eml"
  588. s3.upload_email_from_bytesio(
  589. file_path, BytesIO(orig_msg.as_bytes()), random_name
  590. )
  591. refused_email = RefusedEmail.create(
  592. path=file_path, full_report_path=full_report_path, user_id=user.id
  593. )
  594. db.session.flush()
  595. email_log.refused_email_id = refused_email.id
  596. db.session.commit()
  597. LOG.d("Create refused email %s", refused_email)
  598. refused_email_url = (
  599. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  600. )
  601. # inform user if this is the first bounced email
  602. if nb_bounced == 1:
  603. LOG.d(
  604. "Inform user %s about bounced email sent by %s to alias %s",
  605. user,
  606. contact.website_email,
  607. address,
  608. )
  609. send_email_with_rate_control(
  610. user,
  611. ALERT_BOUNCE_EMAIL,
  612. # use user mail here as only user is authenticated to see the refused email
  613. user.email,
  614. f"Email from {contact.website_email} to {address} cannot be delivered to your inbox",
  615. render(
  616. "transactional/bounced-email.txt",
  617. name=user.name,
  618. alias=alias,
  619. website_email=contact.website_email,
  620. disable_alias_link=disable_alias_link,
  621. refused_email_url=refused_email_url,
  622. mailbox_email=mailbox_email,
  623. ),
  624. render(
  625. "transactional/bounced-email.html",
  626. name=user.name,
  627. alias=alias,
  628. website_email=contact.website_email,
  629. disable_alias_link=disable_alias_link,
  630. refused_email_url=refused_email_url,
  631. mailbox_email=mailbox_email,
  632. ),
  633. # cannot include bounce email as it can contain spammy text
  634. # bounced_email=msg,
  635. )
  636. # disable the alias the second time email is bounced
  637. elif nb_bounced >= 2:
  638. LOG.d(
  639. "Bounce happens again with alias %s from %s. Disable alias now ",
  640. address,
  641. contact.website_email,
  642. )
  643. alias.enabled = False
  644. db.session.commit()
  645. send_email_with_rate_control(
  646. user,
  647. ALERT_BOUNCE_EMAIL,
  648. # use user mail here as only user is authenticated to see the refused email
  649. user.email,
  650. f"Alias {address} has been disabled due to second undelivered email from {contact.website_email}",
  651. render(
  652. "transactional/automatic-disable-alias.txt",
  653. name=user.name,
  654. alias=alias,
  655. website_email=contact.website_email,
  656. refused_email_url=refused_email_url,
  657. mailbox_email=mailbox_email,
  658. ),
  659. render(
  660. "transactional/automatic-disable-alias.html",
  661. name=user.name,
  662. alias=alias,
  663. website_email=contact.website_email,
  664. refused_email_url=refused_email_url,
  665. mailbox_email=mailbox_email,
  666. ),
  667. # cannot include bounce email as it can contain spammy text
  668. # bounced_email=msg,
  669. )
  670. def handle_spam(
  671. contact: Contact,
  672. alias: Alias,
  673. msg: Message,
  674. user: User,
  675. mailbox_email: str,
  676. email_log: EmailLog,
  677. ):
  678. # Store the report & original email
  679. orig_msg = get_orig_message_from_spamassassin_report(msg)
  680. # generate a name for the email
  681. random_name = str(uuid.uuid4())
  682. full_report_path = f"spams/full-{random_name}.eml"
  683. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  684. file_path = None
  685. if orig_msg:
  686. file_path = f"spams/{random_name}.eml"
  687. s3.upload_email_from_bytesio(
  688. file_path, BytesIO(orig_msg.as_bytes()), random_name
  689. )
  690. refused_email = RefusedEmail.create(
  691. path=file_path, full_report_path=full_report_path, user_id=user.id
  692. )
  693. db.session.flush()
  694. email_log.refused_email_id = refused_email.id
  695. db.session.commit()
  696. LOG.d("Create spam email %s", refused_email)
  697. refused_email_url = (
  698. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  699. )
  700. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  701. # inform user
  702. LOG.d(
  703. "Inform user %s about spam email sent by %s to alias %s",
  704. user,
  705. contact.website_email,
  706. alias.email,
  707. )
  708. send_email_with_rate_control(
  709. user,
  710. ALERT_SPAM_EMAIL,
  711. mailbox_email,
  712. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  713. render(
  714. "transactional/spam-email.txt",
  715. name=user.name,
  716. alias=alias,
  717. website_email=contact.website_email,
  718. disable_alias_link=disable_alias_link,
  719. refused_email_url=refused_email_url,
  720. ),
  721. render(
  722. "transactional/spam-email.html",
  723. name=user.name,
  724. alias=alias,
  725. website_email=contact.website_email,
  726. disable_alias_link=disable_alias_link,
  727. refused_email_url=refused_email_url,
  728. ),
  729. )
  730. def handle_unsubscribe(envelope: Envelope):
  731. msg = email.message_from_bytes(envelope.original_content)
  732. # format: alias_id:
  733. subject = msg["Subject"]
  734. try:
  735. # subject has the format {alias.id}=
  736. if subject.endswith("="):
  737. alias_id = int(subject[:-1])
  738. # some email providers might strip off the = suffix
  739. else:
  740. alias_id = int(subject)
  741. alias = Alias.get(alias_id)
  742. except Exception:
  743. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  744. return "550 SL E8"
  745. if not alias:
  746. LOG.warning("No such alias %s", alias_id)
  747. return "550 SL E9"
  748. # This sender cannot unsubscribe
  749. if alias.mailbox_email() != envelope.mail_from:
  750. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  751. return "550 SL E10"
  752. # Sender is owner of this alias
  753. alias.enabled = False
  754. db.session.commit()
  755. user = alias.user
  756. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  757. send_email(
  758. envelope.mail_from,
  759. f"Alias {alias.email} has been disabled successfully",
  760. render(
  761. "transactional/unsubscribe-disable-alias.txt",
  762. user=user,
  763. alias=alias.email,
  764. enable_alias_url=enable_alias_url,
  765. ),
  766. render(
  767. "transactional/unsubscribe-disable-alias.html",
  768. user=user,
  769. alias=alias.email,
  770. enable_alias_url=enable_alias_url,
  771. ),
  772. )
  773. return "250 Unsubscribe request accepted"
  774. def handle(envelope: Envelope, smtp: SMTP) -> str:
  775. """Return SMTP status"""
  776. # unsubscribe request
  777. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  778. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  779. return handle_unsubscribe(envelope)
  780. # Whether it's necessary to apply greylisting
  781. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  782. LOG.warning(
  783. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  784. )
  785. return "421 SL Retry later"
  786. # result of all deliveries
  787. # each element is a couple of whether the delivery is successful and the smtp status
  788. res: [(bool, str)] = []
  789. for rcpt_to in envelope.rcpt_tos:
  790. msg = email.message_from_bytes(envelope.original_content)
  791. # Reply case
  792. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  793. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  794. LOG.debug(">>> Reply phase %s -> %s", envelope.mail_from, rcpt_to)
  795. is_delivered, smtp_status = handle_reply(envelope, smtp, msg, rcpt_to)
  796. res.append((is_delivered, smtp_status))
  797. else: # Forward case
  798. LOG.debug(">>> Forward phase %s -> %s", envelope.mail_from, rcpt_to)
  799. is_delivered, smtp_status = handle_forward(envelope, smtp, msg, rcpt_to)
  800. res.append((is_delivered, smtp_status))
  801. # special handling for self-forwarding
  802. # just consider success delivery in this case
  803. if len(res) == 1 and res[0][1] == _SELF_FORWARDING_STATUS:
  804. LOG.d("Self-forwarding, ignore")
  805. return "250 SL OK"
  806. for (is_success, smtp_status) in res:
  807. # Consider all deliveries successful if 1 delivery is successful
  808. if is_success:
  809. return smtp_status
  810. # Failed delivery for all, return the first failure
  811. return res[0][1]
  812. class MailHandler:
  813. async def handle_DATA(self, server, session, envelope: Envelope):
  814. LOG.debug(
  815. "===>> New message, mail from %s, rctp tos %s ",
  816. envelope.mail_from,
  817. envelope.rcpt_tos,
  818. )
  819. if POSTFIX_SUBMISSION_TLS:
  820. smtp = SMTP(POSTFIX_SERVER, 587)
  821. smtp.starttls()
  822. else:
  823. smtp = SMTP(POSTFIX_SERVER, 25)
  824. app = new_app()
  825. with app.app_context():
  826. return handle(envelope, smtp)
  827. if __name__ == "__main__":
  828. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  829. controller.start()
  830. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  831. if LOAD_PGP_EMAIL_HANDLER:
  832. LOG.warning("LOAD PGP keys")
  833. app = create_app()
  834. with app.app_context():
  835. load_pgp_public_keys(app)
  836. while True:
  837. time.sleep(2)