email_handler.py 33 KB

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